746. Alternating Sum Pick
A trader reviews the daily price changes in nums. She may choose any subsequence of the days (possibly none), keeping their order. The score of a choice is formed by adding the first chosen value, subtracting the second, adding the third, subtracting the fourth, and so on. The score of an empty choice is 0.
Return the largest score any choice can reach. Values may be negative, so picking nothing can sometimes be the best option. The score can be large, so the return type is 64-bit.
Aim for time O(n) and extra space O(1), where n is the length of nums.
Example 1
- Input:
- nums = [6,2,9,1,7]
- Output:
- 19
- Explanation:
Taking every day gives 6 - 2 + 9 - 1 + 7 = 19, and that is the best.
Example 2
- Input:
- nums = [-4,-8,-1]
- Output:
- 4
- Explanation:
Picking -4 and then -8 scores -4 - (-8) = 4, better than any other choice including the empty one.
Example 3
- Input:
- nums = [3,10,3,10,3]
- Output:
- 17
- Explanation:
Picking 10, 3, 10 scores 10 - 3 + 10 = 17.
Constraints
1 ≤ nums.length ≤ 105
-109 ≤ nums[i] ≤ 109
The answer is below 9 * 1015.
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 1,600 msC++ 400 msJava 800 msJavaScript 800 msTypeScript 800 ms
Expected complexity
- Time
- O(n)
- Space
- O(1)