In a distant galaxy, space traders collect rare space gems on different planets. The value of these gems can either be positive (gain) or negative (loss). Find the maximum total value of gems that can be collected along an intergalactic trade route where the value of the gems alternates between gain and loss.
Explanation: Step-by-step: with input [3, -1, 4, -2, 6], we first initialize max_sum and min_sum to the first element of the array, which is 3. Then, we iterate over the array from the second element to the end. When i is even, we update max_sum to be the maximum of the current max_sum and the sum of the current element and the previous max_sum. When i is odd, we update min_sum to be the minimum of the current min_sum and the sum of the current element and the previous min_sum. Finally, we return the maximum of max_sum and min_sum, which is 5.
Explanation: Step-by-step: with input [3, -1, 4, -2, 6, -2, 3], we first initialize max_sum and min_sum to the first element of the array, which is 3. Then, we iterate over the array from the second element to the end. When i is even, we update max_sum to be the maximum of the current max_sum and the sum of the current element and the previous max_sum. When i is odd, we update min_sum to be the minimum of the current min_sum and the sum of the current element and the previous min_sum. Finally, we return the maximum of max_sum and min_sum, which is 5.
Master coding challenges related to Arrays and solve the [Backup] Galactic Trade Route Optimization problem optimally.
No dry run loaded.
🚀 Practice this problem
Run code, get AI hints & track streak