LeetCode-in-Java

3903. Smallest Stable Index I

Easy

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:

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.

Example 1:

Input: nums = [5,0,1,4], k = 3

Output: 3

Explanation:

Example 2:

Input: nums = [3,2,1], k = 1

Output: -1

Explanation:

Example 3:

Input: nums = [0], k = 0

Output: 0

Explanation:

At index 0, the instability score is 0 - 0 = 0, which is less than or equal to k = 0. Therefore, the answer is 0.

Constraints:

Solution

public class Solution {
    public int firstStableIndex(int[] nums, int k) {
        int n = nums.length;
        int[] mini = new int[n];
        int mint = Integer.MAX_VALUE;
        for (int i = n - 1; i >= 0; i--) {
            if (nums[i] < mint) {
                mint = nums[i];
            }
            mini[i] = mint;
        }
        int maxt = 0;
        for (int i = 0; i < n; i++) {
            if (nums[i] > maxt) {
                maxt = nums[i];
            }
            if (maxt - mini[i] <= k) {
                return i;
            }
        }
        return -1;
    }
}