Buy Two Chocolates

Updated on 21 May, 2025
Buy Two Chocolates header image

Problem Statement

In this problem, you are provided with an array of integers called prices, representing the cost of different chocolates in a store. Alongside, you are given a single integer money representing the total amount of money you have. The objective is to purchase exactly two chocolates from this list. However, the sum of the prices of these two chocolates should allow you to have some money left, specifically a non-negative amount. Your goal is to spend as much of your money as possible on these two chocolates without going into debt, thereby minimizing the leftover money after the purchase. If it's not possible to buy two chocolates without exceeding your budget, simply return the initial amount of money you have. The solution should effectively determine the optimal pair of chocolates to purchase, so that the leftover money is minimized.

Examples

Example 1

Input:

prices = [1,2,2], money = 3

Output:

0

Explanation:

Purchase the chocolates priced at 1 and 2 units respectively. You will have 3 - 3 = 0 units of money afterwards. Thus, we return 0.

Example 2

Input:

prices = [3,2,3], money = 3

Output:

3

Explanation:

You cannot buy 2 chocolates without going in debt, so we return 3.

Constraints

  • 2 <= prices.length <= 50
  • 1 <= prices[i] <= 100
  • 1 <= money <= 100

Approach and Intuition

To solve this problem optimally, consider the following approach based on the given constraints:

  1. If there are only two chocolates in the list (prices.length == 2), simply sum their costs. If the sum is less than or equal to money, return the remaining amount after the purchase. If greater, return the initial amount of money as no purchase is possible without debt.
  2. For more chocolates, iterate through each possible combination of two distinct chocolates:
    • For each combination (let’s say chocolates at i and j with i < j), calculate the combined cost.
    • If this combined cost is less than or equal to your money:
      • Check how much money will be leftover after this purchase.
      • Keep track of the maximum amount spent in order to minimize the leftover money.
    • If no valid pairs are found (all combinations exceed the budget), the returned result should be the original amount of money, indicating that no purchase is feasible.

This method ensures that you check all possible pairs and find the one that maximizes your expenditure without going into debt. In computational terms, this algorithm runs in O(n^2) time complexity because every pair of chocolates is considered exactly once, where n refers to the total number of chocolates, which is feasible given the constraint (maximum of 50 chocolates). This brute-force approach ensures that you find the solution by explicitly checking each viable pair.

Solutions

  • C++
  • Java
  • JavaScript
  • Python
cpp
class Solution {
public:
    int purchaseChocolates(vector<int>& costList, int budget) {
        int cheapest = min(costList[0], costList[1]);
        int secondCheapest = max(costList[0], costList[1]);

        for (int idx = 2; idx < costList.size(); idx++) {
            if (costList[idx] < cheapest) {
                secondCheapest = cheapest;
                cheapest = costList[idx];
            } else if (costList[idx] < secondCheapest) {
                secondCheapest = costList[idx];
            }
        }

        int totalMinimumCost = cheapest + secondCheapest;

        if (totalMinimumCost <= budget) {
            return budget - totalMinimumCost;
        }

        return budget;
    }
};

This solution in C++ aims to help determine how many chocolates can be purchased within a given budget. The function purchaseChocolates accepts two parameters: a vector costList that stores the costs of available chocolates, and an integer budget representing the total money available.

  • Follow these steps to understand the functioning of the code:

    1. Initialize two integers, cheapest and secondCheapest, to store the minimum and second minimum values from the first two elements of the costList.
    2. Loop through the costList starting from the third element.
    3. If the current chocolate cost is less than the cheapest, update secondCheapest to be cheapest and then set cheapest to the current cost.
    4. If the current chocolate cost is less than secondCheapest but more than cheapest, update secondCheapest to the current cost.
    5. Calculate the sum of cheapest and secondCheapest.
    6. Check if this total is within the budget.
    7. If the total cost is less than or equal to the budget, return the remaining budget after purchasing the two cheapest chocolates.
    8. If not, return the original budget indicating that it's not possible to buy two chocolates.
  • Key points:

    • The function efficiently finds the two lowest costs using a single pass through the chocolate costs list.
    • It ensures that even with the minimum cost chocolates, the purchase should not exceed the available budget.
    • The solution returns how much budget remains after the potential purchase, or the full budget if a purchase isn't possible, which can help in further planning or decision-making.
java
class Solution {
    public int purchaseChocolate(int[] costs, int budget) {
        int least = Math.min(costs[0], costs[1]);
        int secondLeast = Math.max(costs[0], costs[1]);

        for (int i = 2; i < costs.length; i++) {
            if (costs[i] < least) {
                secondLeast = least;
                least = costs[i];
            } else if (costs[i] < secondLeast) {
                secondLeast = costs[i];
            }
        }

        int totalCost = least + secondLeast;

        if (totalCost <= budget) {
            return budget - totalCost;
        }

        return budget;
    }
}

The Java code provided defines a method purchaseChocolate in a class named Solution that aims to determine how much budget remains after purchasing the two cheapest chocolates from a list of chocolate costs, given a specified budget.

Here's an overview of the steps involved:

  1. Initialize least and secondLeast with the first two elements of the costs array, ensuring they represent the minimum and second minimum values respectively.
  2. Traverse through the chocolate costs array starting from the third element.
  3. Update the least and secondLeast variables appropriately; if a cost in the array is less than least, update both least and secondLeast. If it's only less than secondLeast, update secondLeast.
  4. Once all elements are checked, sum least and secondLeast to get the total cost of the two cheapest chocolates.
  5. If this total cost is within the provided budget, subtract it from the budget to calculate the remaining amount.
  6. Return the remaining budget or, if the total cost exceeds the budget, return the original budget.

This algorithm efficiently finds the two lowest values in a single sweep of the array, ensuring that you can calculate how much budget is left after making the two cheapest purchases within the constraints.

js
var purchaseChocolate = function(costs, budget) {
    // Initialize the lowest and second lowest cost values
    let lowCost = Math.min(costs[0], costs[1]);
    let secondLowCost = Math.max(costs[0], costs[1]);

    // Determine the two lowest costs from the array
    for (let j = 2; j < costs.length; j++) {
        if (costs[j] < lowCost) {
            secondLowCost = lowCost;
            lowCost = costs[j];
        } else if (costs[j] < secondLowCost) {
            secondLowCost = costs[j];
        }
    }

    // Calculate the combined lowest cost
    let totalMinCost = lowCost + secondLowCost;

    // Check financial capability to purchase
    if (totalMinCost <= budget) {
        return budget - totalMinCost;  // Return remaining money after purchase
    }

    return budget;  // Not enough funds, return original budget
};

The problem "Buy Two Chocolates" involves creating a JavaScript function that determines if a user can purchase the two least expensive chocolates from an array of costs, given a specific budget. The function should also calculate the remaining budget after the purchase if feasible.

  • Start by identifying the two least expensive chocolates. Initialize two variables, lowCost and secondLowCost, with the smallest and second smallest values from the first two elements in the array.
  • Iterate over the remaining items in the costs array, updating lowCost and secondLowCost accordingly whenever a new lower or second-lower cost is found.
  • After determining the two lowest prices, sum them to get totalMinCost.
  • If totalMinCost is within the provided budget, calculate and return the remaining amount (budget - totalMinCost) indicating the successful purchase.
  • If the combined price of the two chocolates exceeds the budget, simply return the original budget, indicating that the purchase is not possible without exceeding the budget limit.

This solution efficiently finds the two cheapest items and checks the feasibility of purchasing them within the budget, all while optimizing cost-related decisions.

python
class Solution:
    def purchaseChocolate(self, costs: List[int], budget: int) -> int:
        # Initialize with the first two costs assuming minimum and second minimum
        small = min(costs[0], costs[1])
        second_small = max(costs[0], costs[1])

        # Loop through the prices from the third item
        for cost in costs[2:]:
            if cost < small:
                second_small = small
                small = cost
            elif cost < second_small:
                second_small = cost

        # Calculate the combined cost of the two cheapest chocolates
        total_min_cost = small + second_small

        # Check if the total minimum cost is within the budget
        if total_min_cost <= budget:
            return budget - total_min_cost

        # If not enough budget, return the original budget
        return budget

This Python3 solution outlines a method for determining how much of a given budget remains after purchasing the two cheapest items from a list, specifically chocolates in this case. The method purchaseChocolate accepts a list of integers, costs, which represents the cost of each chocolate, and an integer, budget, representing the buyer's total available funds.

The approach involves:

  • Identifying the two least expensive chocolates.
  • Ensuring their combined cost does not exceed the budget.
  • Returning the remaining budget after these purchases.

Here's a step-by-step breakdown of the implementation:

  1. Initialize two variables small and second_small to the cost of the first and second items respectively, determining which is less expensive.
  2. Iterate through the remaining chocolates' costs.
  3. Update small and second_small appropriately to always hold the lowest and the second lowest costs found so far.
  4. Compute the total cost of the two cheapest chocolates.
  5. Check if the budget can cover this cost. If so, return the remaining budget after the purchase. If not, simply return the total budget, indicating no purchase was made.

This algorithm ensures you spend the least amount possible on the two chocolates, maximizing the remaining budget.

Comments

No comments yet.