In this case what the leetcode problem was about probably doesn’t matter, because it’s not about the algorithm. However it was problem number 3075 just in case you want to check it out. Ok now the problem is the following: I have first version of the code and the second version of the code. The first one doesn’t word for some reason giving the error. Here is the first version of the code. The input is: [7, 50, 3] and k = 3;
class Solution {
public:
long long maximumHappinessSum(vector<int>& happiness, int k) {
sort(happiness.begin(), happiness.end());
long long total = 0;
int count = 0;
for (int i = happiness.size() - 1; i >= happiness.size() - k; i--) {
int toAdd = happiness[i] - count;
if (toAdd <= 0) return total;
total += toAdd;
count++;
}
return total;
}
};
Here is version 2:
class Solution {
public:
long long maximumHappinessSum(vector<int>& happiness, int k) {
sort(happiness.begin(), happiness.end());
long long total = 0;
int count = 0;
int till = happiness.size() - k; // This is the only thing i changed.
for (int i = happiness.size() - 1; i >= till; i--) {
int toAdd = happiness[i] - count;
if (toAdd <= 0) return total;
total += toAdd;
count++;
}
return total;
}
};
I tried printing out the “i” index and “happiness.size() – k” and when it was erroring, i was -1 and happiness.size() – k is always zero. For some unknown reason the programm let through -1 >= 0 and than totally crashed. I also thought that the edgecase was when the length of the given vector was same as k, but it worked on other number like when both the size of the vector and k was 4 or 5, so i ruled that out. I believe that the change I made in the second version of the code shouldn’t have changed anything because I never change the size of the vector or k in my code so value of (happiness.size() – k) should be constant. I want to know why the first version gives out error.
3