Maximum Alternate Chest Sum — Problem Statement & Solution Guide
Problem Description
You are given a 2D array of integers chests where chests[i] represents the number of gems in each chest on planet i. Find the maximum sum of gems that can be collected by visiting a subsequence of planets, where the gems are collected from every other chest, starting from the first chest on each planet.
Examples
Input
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Output
13
Explanation: Step-by-step: For the input [[1, 2, 3], [4, 5, 6], [7, 8, 9]], we start from the first chest on each planet. We collect gems from every other chest, starting from the first chest on each planet. The correct sequence is 1 + 5 + 7 = 13.
Input
[[1, 6, 11], [2, 7, 12], [3, 8, 13]]
Output
18
Explanation: Step-by-step: For the input [[1, 6, 11], [2, 7, 12], [3, 8, 13]], we start from the first chest on each planet. We collect gems from every other chest, starting from the first chest on each planet. The correct sequence is 1 + 6 + 11 = 18.
Constraints
- 1 <= arr.length <= 10^5
- -10^5 <= arr[i] <= 10^5
Optimal Approach & Strategy
The optimized approach utilizes dynamic programming to solve the problem in linear time complexity, O(n). By maintaining two arrays, one for the maximum sum including the current chest and another for the maximum sum excluding the current chest, we can avoid redundant calculations and efficiently compute the maximum sum of gems that can be collected.
Brute Force Approach
The brute-force approach involves calculating the sum of gems for every possible subsequence of chests and then selecting the maximum sum. This can be achieved by generating all possible subsequences and iterating through the array to calculate the sum for each subsequence, resulting in a time complexity of O(2^n). This approach is inefficient and not suitable for large inputs.
Verified Code Solutions
function maxAlternateChestSum(chests) {
let maxSum = 0;
for (let i = 0; i < chests.length; i++) {
for (let j = 0; j < chests[i].length; j += 2) {
maxSum += chests[i][j];
}
}
return maxSum;
}class Solution {
public int maxAlternateChestSum(int[][] chests) {
int max_sum = 0;
for (int[] planet : chests) {
max_sum += Math.max(planet[0], planet[2]);
}
return max_sum;
}
}def maxAlternateChestSum(chests):
max_sum = 0
for planet in chests:
max_sum += max(planet[::2])
return max_sumfunction maxAlternateChestSum(chests) {
let maxSum = 0;
for (let i = 0; i < chests.length; i++) {
for (let j = 0; j < chests[i].length; j += 2) {
maxSum += chests[i][j];
}
}
return maxSum;
}Asked in Top Tech Interviews
Solve in Interative Editor
Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.