Opening the reading…
Opening the reading…
GREEDY › PART I
Open — the attempt gate is not wired up yet
This editorial is meant to unlock after you have run the problem at least once, with the worked solution behind one further deliberate click. That needs per-learner unlock state nothing stores today, so for now the whole article is open.
Try it yourself first →Look at one position and compute diff = nums1[i] - nums2[i]. If diff is positive, that position has diff extra value and must give away diff units. If diff is negative, it needs -diff units. One operation transfers exactly k units from one position to another, so every required change must be divisible by k.
After converting each difference into operations, add the requirements on both sides. The total number of units that must be removed must equal the total number that must be added; otherwise no sequence of transfers can finish the job. When the two totals match, each operation can pair one required decrement with one required increment, so the number of operations is exactly that common total.
| MEASURE | BOUND | WHY |
|---|---|---|
| Time | O(n) | The scan processes each corresponding pair once, performing only constant-time arithmetic and checks per index, so no element is revisited or compared with every other element. |
| Space | O(1) extra | Only the counters and one difference are stored. The returned number is a scalar output, not working memory, and this bound does not degrade for any input shape. |
#include <vector>
using namespace std;
class Solution {
public:
long long minOperations(vector<int>& nums1, vector<int>& nums2, int k) {
long long pos = 0;
long long neg = 0;
for (int i = 0; i < static_cast<int>(nums1.size()); ++i) {
int diff = nums1[i] - nums2[i];
if (diff == 0) {
continue;
}
if (k == 0 || diff % k != 0) {
return -1;
}
if (diff > 0) {
pos += diff / k;
} else {
neg += (-diff) / k;
}
}
if (pos != neg) {
return -1;
}
return pos;
}
};The two counters are deliberately long long. A single difference fits in an int, but the sum of up to n differences divided by k can be much larger than a 32-bit signed integer. The final equality check is the conservation rule: every unit removed from one index must be added to another, so equal totals are both necessary and sufficient.