1+ package LeetCode .Arrays ;
2+
3+ public class LeetCode_3904_SmallestStableIndex_II {
4+ public static void main (String [] args ) {
5+ int [] nums = {10 , 5 , 7 , 6 , 8 };
6+ int k = 2 ;
7+ System .out .println (firstStableIndex (nums , k ));
8+ }
9+
10+ /*
11+ Approach: Suffix Minimum + Prefix Maximum
12+ For every index i, we need: max(nums[0...i]) - min(nums[i...n-1]) <= k
13+ 1. Build a suffix minimum array where minValue[i] stores the minimum value from index i to the end.
14+ 2. Traverse from left to right while maintaining the maximum value seen so far.
15+ 3. At each index, check whether the difference between the prefix maximum and suffix minimum is <= k.
16+ 4. The first valid index is the smallest stable index.
17+ */
18+ static int firstStableIndex (int [] nums , int k ) {
19+ int n = nums .length ;
20+
21+ // Store minimum value from each index to the end.
22+ int [] minValue = new int [n ];
23+ minValue [n - 1 ] = nums [n - 1 ];
24+ for (int i = n - 2 ; i >= 0 ; i --) {
25+ minValue [i ] = Math .min (minValue [i + 1 ], nums [i ]);
26+ }
27+
28+ // Track maximum value from the beginning up to index i.
29+ int maxValue = 0 ;
30+ for (int i = 0 ; i < n ; i ++) {
31+ maxValue = Math .max (maxValue , nums [i ]);
32+ if (maxValue - minValue [i ] <= k ) {
33+ return i ;
34+ }
35+ }
36+ return -1 ;
37+ }
38+ }
39+
40+ /*
41+ ---------------------------------------------------------
42+ Complexity Analysis
43+ ---------------------------------------------------------
44+
45+ Time Complexity: O(n)
46+
47+ - Building the suffix minimum array takes O(n).
48+ - Finding the first stable index takes O(n).
49+
50+ Space Complexity: O(n)
51+
52+ - The suffix minimum array requires O(n) extra space.
53+
54+ Key Observation: For index i, the stability condition can be checked as: max(nums[0...i]) - min(nums[i...n-1]) <= k
55+
56+ By maintaining the prefix maximum and precomputing suffix minimums, every index can be checked in O(1).
57+ ---------------------------------------------------------
58+ */
0 commit comments