Minimum Increment to Make Array Unique | Leetcode #945

preview_player
Показать описание
Minimum Increment to Make Array Unique.

Today we'll be looking at two potential solutions at determining the minimum increment to make array unique.

You can find the problem statement on leetcode:
Рекомендации по теме
Комментарии
Автор

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
Автор

good vid, but i didnt understand the logic

premthapa
Автор

May I ask why do you use len(A)*2? what if A = [100, 100, 1]?

shrimpo
Автор

Hi! What do you think would be the solution if every element would have a cost for increment with one unit?

mihailmihai
Автор

Can I asked why did you stop working on robin hoops?

NastyStacks
visit shbcf.ru