Leetcode 945 Minimum Increment to Make Array Unique

preview_player
Показать описание
Рекомендации по теме
Комментарии
Автор

Initially, I thought of using Next Greater to Left & Next Greater to Right concepts, & did dry run as per below written code for the test cases, [1, 2, 2], [3, 2, 1, 2, 1, 7] & [4, 4, 4, 4, 4]. According to the dry run, I got the correct answers, but when I run the test cases on leetcode, I get correct output for [1, 2, 2], but for [3, 2, 1, 2, 1, 7] & [4, 4, 4, 4, 4], it shows output of 4, which is wrong. My dry run (as per the same code) yielded correct answer, but on running on platform, it fails. Can anyone help me address this issue ? The code is :

class Solution {
private:
vector<int> NGR(vector<int>& arr, int n){
stack<int> st;
vector<int> result(n, -1);

for (int i = n - 1; i >= 0; i--) {
while (!st.empty() && st.top() <= arr[i]) {
st.pop();
}
if (!st.empty()) {
result[i] = st.top();
}
st.push(arr[i]);
}
return result;
}
vector<int> NGL(vector<int>& arr, int n){
stack<int> st;
vector<int> result(n, -1);

for (int i = 0; i < n; i++) {
while (!st.empty() && st.top() <= arr[i]) {
st.pop();
}
if (!st.empty()) {
result[i] = st.top();
}
st.push(arr[i]);
}
return result;
}
public:
int nums) {
int n = nums.size();
vector<int> ngr = NGR(nums, n);
vector<int> ngl = NGL(nums, n);
set<int> st;
int minMoves = 0;

for(int i = 0; i < n; i++){
int num = nums[i];
if(st.find(num) == st.end()) st.insert(num);
else{
int gRight = ngr[i];
int gLeft = ngl[i];
// 4 cases
// case - 1
if(gRight == -1 && gLeft == -1){
minMoves++;
num++;
}
// case - 2
else if(min(gRight, gLeft) == -1){
minMoves += max(gRight, gLeft) + 1 - num;
num = max(gRight, gLeft) + 1;
}
// case - 3 & 4
else if(min(gRight, gLeft) != -1){
int diff = abs(gRight - gLeft);
if(diff > 1){
minMoves += min(gRight, gLeft) + 1 - num;
num = min(gRight, gLeft) + 1;
}
else if(diff == 1){
minMoves += max(gRight, gLeft) + 1 - num;
num = max(gRight, gLeft) + 1;
}
}
}
}
return minMoves;
}
};

imPriyansh
Автор

Brilliant and easy to understand. Thank you

nickx
welcome to shbcf.ru