[LeetCode] Maximum Value of an Alternating Sequence

3993. Maximum Value of an Alternating Sequence

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] > ..., or
    • seq[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.

1
2
3
4
5
6
class Solution {
public:
long long maximumValue(int n, int s, int m) {
return n == 1 ? s : s + ((n / 2 - 1) * 1ll * (m - 1)) + (n / 2 ? m : 0);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/maximum-value-of-an-alternating-sequence/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.