Maximum Value of an Alternating Sequence Problem
Description
LeetCode Problem 3993.
You are given three integers n, s, and m.
A sequence seq of integers of length n is considered valid if:
seq[0] = s.- The sequence is alternating, meaning that either:
seq[0] > seq[1] < seq[2] > ..., orseq[0] < seq[1] > seq[2] < ....
- For every adjacent pair,
|seq[i] - seq[i - 1]| <= m.
A sequence of length 1 is considered alternating.
Return the maximum possible element that can appear in any valid sequence.
Example 1:
Input: n = 4, s = 3, m = 5
Output: 12
Explanation:
- One valid sequence is [3, 8, 7, 12].
- The maximum element in the sequence is 12.
Example 2:
Input: n = 2, s = 4, m = 3
Output: 7
Explanation:
- One valid sequence is [4, 7].
- The maximum element in the sequence is 7.
Constraints:
1 <= n, s <= 10^91 <= m <= 10^5
Solution
Approach: Greedy
If n = 1, the sequence is just s, so the answer is s.
Otherwise, to reach the largest value we should repeatedly rise by m and then fall by only 1. The fall must be at least 1 because the sequence strictly alternates, and a small fall keeps the next rise as high as possible. The sequence looks like
s, s + m, s + m - 1, s + 2m - 1, s + 2m - 2, ...
With length n we can make floor(n / 2) rises. After the k-th rise the value is s + k * (m - 1) + 1, so the maximum element is s + floor(n / 2) * (m - 1) + 1. Starting with a fall only lowers every later value, so this is optimal.
Complexity: time O(1), space O(1).
class Solution:
def maximumValue(self, n: int, s: int, m: int) -> int:
if n == 1:
return s
return s + n // 2 * (m - 1) + 1