Ctrl K

Pick and Alternate

Medium
You are given an array of positive integers values. Choose a non-empty subsequence: some of the elements in their original order, not necessarily adjacent. Then give them alternating signs: the first one plus, the second minus, the third plus, and so on. Return the largest sum you can get this way.
Example 1
values=[7, 3, 8, 1, 4] → 15

Taking every number is best: 7 - 3 + 8 - 1 + 4 = 15.

Example 2
values=[2, 9, 5] → 9

Taking just 9 is enough. For example, [9, 5] would give only 4.

Example 3
values=[5, 1, 5, 1, 5] → 13
Constraints
  • 1 ≤ len(values) ≤ 10⁵
  • 1 ≤ values[i] ≤ 10⁵
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsFewest Jumps to the End MediumMost Profitable Streak MediumReach the Last Cell MediumWarehouse Cart Routes MediumCheapest Corner-to-Corner Route Medium
loading Python…
Input
values=[7, 3, 8, 1, 4]
Expected
15

Run checks the first 3 tests in your browser. Submit checks all 95 tests on the server, hidden ones included.