710108. Wine Buying and Selling

Medium

Here is the detailed Markdown blog post for the Wine Buying and Selling problem:

Wine Buying and Selling

Summary

The problem is about buying and selling wine. You are given an array wine representing the available wine quantities at a store, and another array orders containing the customer orders in descending order of quantity. Your task is to determine the minimum number of bottles needed to satisfy all the orders while minimizing waste.

Detailed Explanation

The algorithmic approach involves using a greedy strategy to solve this problem. We iterate through the orders array from left to right, and for each order, we check if it can be satisfied by the available wine quantities in the wine array. If an order cannot be fully satisfied, we calculate the maximum number of bottles that can be sold without exceeding the available quantity.

Here is a step-by-step breakdown of the solution:

  1. Initialize two variables: min_bottles to keep track of the minimum number of bottles needed and remaining_wine to store the remaining wine quantity.
  2. Iterate through the orders array from left to right:
    • For each order, calculate the maximum number of bottles that can be sold without exceeding the available quantity: max_bottles = min(available_wine, order_quantity).
    • Update the remaining_wine: remaining_wine -= max_bottles * order_quantity.
    • Add max_bottles to the min_bottles count.
  3. If there is still wine left (remaining_wine > 0), it means that some orders were not fully satisfied, and we need to calculate the minimum number of bottles needed for those orders.

Time complexity: O(n), where n is the length of the orders array. Space complexity: O(1), as we only use a few extra variables to store intermediate results.

Optimized Solutions

Java

View on GeeksforGeeks
public int minBottles(int[] wine, int[] orders) {
    int minBottles = 0;
    int remainingWine = 0;
    for (int order : orders) {
        int maxBottles = Math.min(wine[0], order);
        remainingWine -= maxBottles * order;
        minBottles += maxBottles;
        wine[0] -= maxBottles;
    }
    return minBottles;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.