BackmediumArraysPhonePePayPal

Alternating Sum Maximization 2 Solution

Problem Statement

Given an array of integers values, find the maximum total value that can be obtained by alternating between adding and subtracting consecutive elements. The sequence of additions and subtractions must start with an addition.

Example 1
Input
[12, -34, 5]
Output
-27

Explanation: Step-by-step: Given array [12, -34, 5], we start with addition: 12 + (-34) = -22. Then, we subtract: -22 - 5 = -27.

Example 2
Input
[-12, -34, 5]
Output
-51

Explanation: Step-by-step: Given array [-12, -34, 5], we start with addition: -12 + (-34) = -46. Then, we subtract: -46 - 5 = -51.

Constraints

  • 1 <= array length <= 1000
  • -1000 <= array element <= 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 Maximization 2 — Problem Statement & Solution Guide

ArraysMediumMixed
TimeO(n)
|
SpaceO(1)

Problem Description

Given an array of integers values, find the maximum total value that can be obtained by alternating between adding and subtracting consecutive elements. The sequence of additions and subtractions must start with an addition.

Examples

Example 1

Input

[12, -34, 5]

Output

-27

Explanation: Step-by-step: Given array [12, -34, 5], we start with addition: 12 + (-34) = -22. Then, we subtract: -22 - 5 = -27.

Example 2

Input

[-12, -34, 5]

Output

-51

Explanation: Step-by-step: Given array [-12, -34, 5], we start with addition: -12 + (-34) = -46. Then, we subtract: -46 - 5 = -51.

Constraints

  • 1 <= array length <= 1000
  • -1000 <= array element <= 1000

Verified Code Solutions

JavaScript Solution
Time: O(n)
function alternatingSumMaximization2(values) {
  if (values.length === 0) return 0;
  let sum = values[0];
  let min = Infinity;
  let add = true;
  for (let i = 1; i < values.length; i++) {
    if (add) {
      sum += values[i];
    } else {
      sum = Math.max(sum - values[i], min + values[i]);
      min = Math.min(min, sum - values[i]);
    }
    add = !add;
  }
  return sum;
}

Asked in Top Tech Interviews

PhonePePayPal

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.