[translate by ChatGPT]
Although my algorithm was already O(n), I realized I was doing a lot of unnecessary work during the process.
I didn’t actually need to compute the maximum and minimum for every previous position. As soon as I find a valid answer, I can return immediately, which saves a lot of time.
I don’t need to store the maximum number itself — I can just keep track of the index and look it up later. I suspect using a vector to store extra values introduces some overhead.
I also noticed that initializing vectors takes time. I switched to using push_back() instead, since I only access previous positions anyway.
All these small changes together resulted in about a 4× speed improvement.
Later, I saw other solutions that simply maintain the maximum and minimum before prevIdx on the fly. That might be even faster.
Code
class Solution {
public:
vector<int> findIndices(vector<int>& nums, int indexDifference, int valueDifference) {
int n = nums.size();
int maxNum = INT_MIN, maxIdx = -1;
int minNum = INT_MAX, minIdx = -1;
vector<int> maxIdxAry;
vector<int> minIdxAry;
for(int i = 0 ; i < n ; ++i){
if(nums[i] < minNum) {
minNum = nums[i];
minIdx = i;
}
if(nums[i] > maxNum) {
maxNum = nums[i];
maxIdx = i;
}
minIdxAry.push_back(minIdx);
maxIdxAry.push_back(maxIdx);
int prevIdx = i - indexDifference;
if(prevIdx < 0) continue;
int upDiff = nums[maxIdxAry[prevIdx]] - nums[i];
int downDiff = nums[i] - nums[minIdxAry[prevIdx]];
if(upDiff >= valueDifference) {
return {maxIdxAry[prevIdx],i};
}
if(downDiff >= valueDifference) {
return {minIdxAry[prevIdx],i};
}
}
return {-1,-1};
}
};