BackmediumArrays Adobe

Galactic Trade Route Optimization 4 Solution

Problem Statement

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.

Example 1
Input
[3, -1, 4, -2, 6]
Output
5

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.

Example 2
Input
[3, -1, 4, -2, 6, -2, 3]
Output
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.

Constraints

  • 1 <= array length <= 1000
  • -1000 <= array element <= 1000
Live Compiler
Loading...
Test Cases & Output
🔒 Sign up to run your code

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free