algoadvance

Leetcode 3074. Apple Redistribution into Boxes

Problem Statement

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.

Example

Input:

apples = [10, 5, 6, 3, 8]
k = 5

Output:

10

Explanation:

  1. Take 5 apples from the first box and put them into other boxes.
  2. Similarly redistribute other apples till each box has at most k apples.

Clarifying Questions

  1. Clarify the input constraints:
    • What is the maximum length of the apples array? Are all elements non-negative integers?
    • What is the value range for k?
  2. Details about output:
    • Should the result always be printed, or returned by a function?
    • How do you handle edge cases like when k is very large compared to the number of apples in boxes?

Strategy

  1. First, find out how many apples need to be removed from boxes having more than k apples.
  2. Calculate the total number of excess apples by summing the amounts by which each overloaded box exceeds k.
  3. Distribute these excess apples in boxes that have less than k apples.
  4. Accumulate the number of moves required.

Time Complexity

Code

#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.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI