A daily question ---- 2905. Find the subscript that satisfies the difference condition II

This question contains an absolute value difference question. It looks like a double pointer question at first glance, and it also has two restrictions. So our approach is

Fix a condition and maintain a condition

This question also uses a greedy idea, which will be introduced

So how do we fix a condition and maintain a condition?

And which condition is better to fix and which condition to maintain?

1. If it is a fixed size and the subscript is maintained, then we need to sort it first before using double pointers.

2. If it is a fixed subscript and maintained size, then we do not need to sort, then the time complexity is better than the first method, choose the second method

How do we maintain the size here? (If it is an enumeration j and the subscript of j is fixed, then we need to calculate the maximum and minimum values ​​​​in the valid range before i and i. If the previous maximum and minimum values ​​match, then we meet it)

So how do we explain that as long as the maximum and minimum values ​​​​match us, it is consistent, because abs(? - nums[j]) If we want val to be the largest, then what is needed? The largest or smallest difference can be maximized (this is greedy)

We enumerate the subscript j, then we can know that i <= j - indexDifference, calculate i, and then i and j are fixed like a sliding window

left and right, and then record the maximum and minimum values ​​of i and the number before i, because the i subscript and the number before i subscript must meet our subscript conditions (then this is how we have fixed the first condition , maintain the size value), because we know the subscript

number, then we maintain the subscripts of the maximum and minimum values

class Solution {
public:
    vector<int> findIndices(vector<int>& nums, int indexDifference, int valueDifference) 
    {
            int  n = nums.size();
            int min_index = 0;
            int max_index = 0;
            vector<int> ans;
            for(int j = indexDifference;j < n;j++)
            {
               int i = j - indexDifference;

               if(nums[i] > nums[max_index]) max_index = i;
               if(nums[i] < nums[min_index]) min_index = i;
               
               if (abs(nums[j] - nums[min_index]) >= valueDifference) return {min_index, j};
               if (abs(nums[j] - nums[max_index]) >= valueDifference) return {max_index, j};
            }

            return {-1,-1};
    }
};

Guess you like

Origin blog.csdn.net/txh1873749380/article/details/134313430