Leetcode 3074. Apple Redistribution into Boxes
You are given an array apples
where apples[i]
denotes the number of apples in the i-th box. You need to redistribute the apples such that each box has at most k
apples. Determine the minimum number of moves required to achieve this, where each move consists of taking an apple from one box and putting it into another box.
Input:
apples = [10, 5, 6, 3, 8]
k = 5
Output:
10
Explanation:
k
apples.k
?k
is very large compared to the number of apples in boxes?k
apples.k
.k
apples.n
is the number of boxes. This complexity arises from the need to make a single pass through the list to calculate the excess apples and effective redistributions.#include <iostream>
#include <vector>
int minMovesToRedistributeApples(std::vector<int>& apples, int k) {
int moves = 0;
int excess = 0;
for (int appleCount : apples) {
if (appleCount > k) {
excess += (appleCount - k);
}
}
for (int appleCount : apples) {
if (appleCount < k && excess > 0) {
int needed = k - appleCount;
int taken = std::min(needed, excess);
moves += taken;
excess -= taken;
}
}
// Final adjustment to ensure all excesses are accounted as moves
moves += excess;
return moves;
}
int main() {
std::vector<int> apples = {10, 5, 6, 3, 8};
int k = 5;
std::cout << minMovesToRedistributeApples(apples, k) << std::endl; // Output: 10
return 0;
}
This function calculates the minimum moves required to ensure that no box has more than k
apples by redistributing the excess apples to other boxes.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?