BackmediumArrays Amazon

Galactic Trade Route Optimization Solution

Problem Statement

Given an array of fuel level changes, find the maximum sum of a subarray where the signs of the fuel level changes alternate, ending with either a positive or negative value.

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

Explanation: Step-by-step: Given the input [3, -5, 2, -7, 4], we first initialize two variables, max_sum and current_sum, to 0. We then iterate over the array, updating current_sum to be the maximum of 0 and current_sum + nums[i]. If current_sum is greater than max_sum, we update max_sum to be current_sum. We also check if the sign of current_sum and nums[i] are different, and if so, we update max_sum to be the maximum of max_sum and current_sum. Finally, we return max_sum. In this case, the subarray [3, -5, 2, -7, 4] ends with a positive value, so we return 11.

Example 2
Input
[-8, 7, 3, -2]
Output
13

Explanation: Step-by-step: Given the input [-8, 7, 3, -2], we first initialize two variables, max_sum and current_sum, to 0. We then iterate over the array, updating current_sum to be the maximum of 0 and current_sum + nums[i]. If current_sum is greater than max_sum, we update max_sum to be current_sum. We also check if the sign of current_sum and nums[i] are different, and if so, we update max_sum to be the maximum of max_sum and current_sum. Finally, we return max_sum. In this case, the subarray [-8, 7, 3, -2] ends with a negative value, so we return 13.

Constraints

  • Input array will have at least one element and at most 100 elements.
  • Each element in the array will be an integer between -1000 and 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