Leetcode 3074. Apple Redistribution into Boxes
You are given an integer array apples
where apples[i]
represents the number of apples in the i-th
box. Your task is to redistribute the apples in the boxes such that no box has more than a certain number of apples (maxApples
). Each redistributable move consists of moving one apple from one box to another.
Given apples
and maxApples
, return the minimum number of moves required to achieve the goal.
apples
and maxApples
are both non-negative integers?
apples
and maxApples
are non-negative.maxApples
to be smaller than the count of apples in the smallest box?
apples
(n) and the values within apples
?
1 ≤ n ≤ 10^5
and 0 ≤ apples[i] ≤ 10^9
).maxApples
?
maxApples
: First, we identify all the boxes that have more apples than maxApples
.maxApples
, calculate the excess number of apples.maxApples
limit.public class AppleRedistribution {
public int minMoves(int[] apples, int maxApples) {
int excessApples = 0;
int moves = 0;
for (int apple : apples) {
if (apple > maxApples) {
excessApples += apple - maxApples;
}
}
for (int apple : apples) {
if (apple < maxApples) {
int need = maxApples - apple;
int canTake = Math.min(need, excessApples);
moves += canTake;
excessApples -= canTake;
}
}
return moves;
}
public static void main(String[] args) {
AppleRedistribution redist = new AppleRedistribution();
int[] apples = {5, 8, 6, 7, 3, 2}; // Example input
int maxApples = 6;
int result = redist.minMoves(apples, maxApples);
System.out.println("Minimum moves required: " + result);
}
}
O(n)
where n
is the length of the apples
array.O(n)
for iterating through the apples to balance the boxes.O(n)
.This solution efficiently handles the problem within linear time complexity, making it suitable for large arrays.
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?