3074. Apple Redistribution into Boxes
UnknownView on LeetCode
Time: O(n log C)
Space: O(1)
Advertisement
Approach
Binary search on box capacity; validate smallest boxes can hold all grouped apples.
Key Techniques
Array
Array problems involve manipulating elements stored in a contiguous block of memory. Key techniques include two-pointer traversal, prefix sums, sliding windows, and in-place partitioning. In C#, arrays are zero-indexed and fixed in size — use List<T> when you need dynamic resizing.
Greedy
Greedy algorithms make locally optimal choices at each step, hoping to reach a global optimum. Greedy works when a problem has the "greedy choice property" and "optimal substructure". Common applications: interval scheduling, activity selection, Huffman coding, and jump game.
3074.cs
C#
// Approach: Binary search on box capacity; validate smallest boxes can hold all grouped apples.
// Time: O(n log C) Space: O(1)
public class Solution
{
public int MinimumBoxes(int[] apple, int[] capacity)
{
int appleSum = apple.Sum();
int capacitySum = 0;
Array.Sort(capacity);
for (int i = 0; i < capacity.Length; ++i)
{
capacitySum += capacity[capacity.Length - 1 - i];
if (capacitySum >= appleSum)
return i + 1;
}
return capacity.Length;
}
}Advertisement
Was this solution helpful?