BackmediumArrays PhonePe Zomato

Optimizing Galactic Trade Routes Solution

Problem Statement

Given an array of asteroid values where positive values represent valuable resources and negative values represent hazardous asteroids, find the maximum sum of a subarray that alternates between valuable and hazardous asteroids. The subarray must start with a valuable asteroid and alternate between valuable and hazardous asteroids.

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

Explanation: Step-by-step: We start with a valuable asteroid 3. Then we find the next hazardous asteroid -5. The sum of the subarray [3, -5] is -2. We continue this process and find the subarray [1, -2, 3, -4, 5] with a sum of 3. However, we can extend this subarray to [1, -2, 3, -4, 5, -6] with a sum of 0, and further extend it to [1, -2, 3, -4, 5, -6, 7] with a sum of 5, which is the maximum.

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

Explanation: Step-by-step: We start with a valuable asteroid 1. Then we find the next hazardous asteroid -2. The sum of the subarray [1, -2] is -1. We continue this process and find the subarray [1, -2, 3, -4, 5] with a sum of 3. However, we can extend this subarray to [1, -2, 3, -4, 5, -6] with a sum of 0, and further extend it to [1, -2, 3, -4, 5, -6, 7] with a sum of 5, which is the maximum.

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