[LeetCode] Smallest Stable Index I

3903. Smallest Stable Index I

You are given an integer array nums of length n and an integer k.

For each index i, define its instability score as max(nums[0..i]) - min(nums[i..n - 1]).

In other words:

  • max(nums[0..i]) is the largest value among the elements from index 0 to index i.
  • min(nums[i..n - 1]) is the smallest value among the elements from index i to index n - 1.

An index i is called stable if its instability score is less than or equal to k.

Return the smallest stable index. If no such index exists, return -1.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
int firstStableIndex(vector<int>& nums, int k) {
int n = nums.size();
vector<int> ma(n,nums.front()), mi(n,nums.back());
for(int i = 1; i < n; i++) ma[i] = max(nums[i], ma[i-1]);
for(int i = n - 2; i >= 0; i--) mi[i] = min(nums[i], mi[i+1]);
for(int i = 0; i < n; i++) {
if(ma[i] - mi[i] <= k) return i;
}
return -1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/smallest-stable-index-i/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.