2905. Find Indices With Index and Value Difference II

T: O(n)
S: O(1)
```java
class Solution {
    public int[] findIndices(int[] nums, int idxDiff, int valueDiff) {
        int n = nums.length;
        int maxIdx = 0;
        int minIdx = 0;
        int max = nums[0];
        int min = nums[0];
        //.       x
        // [5,1,4,1]
        for (int i = idxDiff; i < n; i++) { // start from diff
            if (nums[i - idxDiff] > max) { // find current max, max = 5
                max = nums[i - idxDiff];
                maxIdx = i - idxDiff;
            }
            if (nums[i - idxDiff] < min) { // find current min, min = 1, minidx = 3
                min = nums[i - idxDiff];
                minIdx = i - idxDiff;
            }
            if (Math.abs(nums[i] - nums[maxIdx]) >= valueDiff) { // check abs(current - max), 5 - 1 = 4
                return new int[] {maxIdx, i};
            }
            if (Math.abs(nums[i] - nums[minIdx]) >= valueDiff) { // check abs(current - min)
                return new int[] {minIdx, i};
            }
        }
        return new int[] {-1, -1};
    }
}

/**
actually a min max problem

T: O(n)
S: O(1)
 */
```

using TreeMap

mimic for 2817

T: O(nlogn)

S: O(n)

class Solution {
    public int[] findIndices(int[] nums, int indexDifference, int valueDifference) {
        TreeMap<Integer, Integer> seen = new TreeMap<>();
        //int result = Integer.MAX_VALUE;
        for (int i = indexDifference; i < nums.length; i++) {
            seen.put(nums[i-indexDifference], i-indexDifference);
            int cur = nums[i];

            Integer first = seen.firstKey();
            if (first != null && Math.abs(first - cur) >= valueDifference) {
                return new int[]{seen.get(first), i};
            }
            Integer last = seen.lastKey();
            if (last != null && Math.abs(last - cur) >= valueDifference) {
                return new int[]{seen.get(last), i};
            }
        }
        return new int[]{-1,-1};
    }
}

/**
Input: nums = [5,1,4,1], indexDifference = 2, valueDifference = 4

[0,3]

no ans[-1,-1]



*/

Last updated