BackmediumArrays Amazon

Galactic Expedition Budgeting Solution

Problem Statement

Given an array of expenses where positive values represent surplus and negative values represent deficit, determine the maximum possible sum of alternating budget periods where the first period has a surplus, the second has a deficit, and this pattern continues.

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

Explanation: Step-by-step: Given the input array [3, -5, 7, -2, 4, -1], we start with a surplus of 3. Then we have a deficit period, so we subtract the sum of -5 and 7 from the current sum, which is -12. Adding -2 to the current sum results in -12 + -2 = -14. Subtracting 4 from the current sum results in -14 - 4 = -18. Finally, adding -1 to the current sum results in -18 + -1 = -19. However, we should have added 3 to the current sum initially, then subtracted -12, then added -2, then subtracted 4, and finally added -1. This results in 3 - 12 - 2 - 4 - 1 = -16.

Example 2
Input
[5, -3, 8, -2, 1]
Output
17

Explanation: Step-by-step: Given the input array [5, -3, 8, -2, 1], we start with a surplus of 5. Then we have a deficit period, so we subtract -3 from the current sum, which is 5 + 3 = 8. Adding 8 to the current sum results in 8 + 8 = 16. Subtracting -2 from the current sum results in 16 + 2 = 18. Subtracting 1 from the current sum results in 18 - 1 = 17.

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