BackmediumArraysSalesforceMicrosoft

Alternating Sum Subarray Maximum Solution

Problem Statement

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

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

Explanation: Step-by-step: with input [1, -2, 3, -4, 5], we first find all possible subarrays with alternating signs. Then, we calculate the sum of each subarray. Finally, we return the maximum sum, which is 2.

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

Explanation: Step-by-step: with input [2, 4, -3, -1, 5], we first find all possible subarrays with alternating signs. Then, we calculate the sum of each subarray. Finally, we return the maximum sum, which is 7.

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 Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Alternating Sum Subarray Maximum — Problem Statement & Solution Guide

ArraysMediumAlternating sum subarray
TimeO(n)
|
SpaceO(1)

Problem Description

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

Examples

Example 1

Input

[1, -2, 3, -4, 5]

Output

2

Explanation: Step-by-step: with input [1, -2, 3, -4, 5], we first find all possible subarrays with alternating signs. Then, we calculate the sum of each subarray. Finally, we return the maximum sum, which is 2.

Example 2

Input

[2, 4, -3, -1, 5]

Output

7

Explanation: Step-by-step: with input [2, 4, -3, -1, 5], we first find all possible subarrays with alternating signs. Then, we calculate the sum of each subarray. Finally, we return the maximum sum, which is 7.

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.

Verified Code Solutions

JavaScript Solution
Time: O(n)
function maxAlternatingSum(arr) { if (arr.length === 0) return 0; let maxSum = -Infinity; for (let i = 0; i < arr.length; i++) { let sum = 0; let sign = 1; for (let j = i; j < arr.length; j++) { sum += sign * arr[j]; sign *= -1; if (sign === 1) { maxSum = Math.max(maxSum, sum); } else { maxSum = Math.max(maxSum, -sum); } } } return maxSum; }

Asked in Top Tech Interviews

SalesforceMicrosoft

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.