Skip to content

Commit

Permalink
update: LC2903: find indices w/ index val diffs satisfies.[E]
Browse files Browse the repository at this point in the history
two pointers, time: O(N), space O(1)
  • Loading branch information
aucker committed May 25, 2024
1 parent dbd95fe commit 6884233
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions daily/May25.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
#include <vector>
using namespace std;

class Solution {
public:
/**
* LC:2903: Find indices w/ index and val diffs
* Time: O(N - indexDifference)
* Space: O(1)
*/
vector<int> findIndices(vector<int>& nums, int indexDifference,
int valueDifference) {
int max_idx = 0, min_idx = 0;
for (int j = indexDifference; j < nums.size(); j++) {
int i = j - indexDifference;
if (nums[i] > nums[max_idx]) {
max_idx = i;
} else if (nums[i] < nums[min_idx]) {
min_idx = i;
}

if (nums[max_idx] - nums[j] >= valueDifference) {
return {max_idx, j};
}
if (nums[j] - nums[min_idx] >= valueDifference) {
return {min_idx, j};
}
}
return {-1, -1};
}
};

0 comments on commit 6884233

Please sign in to comment.