Skip to main content

Command Palette

Search for a command to run...

Buy Two Chocolates

Published
1 min read
Buy Two Chocolates
G

As a Systems Engineer at Tata Consultancy Services, I deliver exceptional software products for mobile and web platforms, using agile methodologies and robust quality maintenance. I am experienced in performance testing, automation testing, API testing, and manual testing, with various tools and technologies such as Jmeter, Azure LoadTest, Selenium, Java, OOPS, Maven, TestNG, and Postman.

I have successfully developed and executed detailed test plans, test cases, and scripts for Android and web applications, ensuring high-quality standards and user satisfaction. I have also demonstrated my proficiency in manual REST API testing with Postman, as well as in end-to-end performance and automation testing using Jmeter and selenium with Java, TestNG and Maven. Additionally, I have utilized Azure DevOps for bug tracking and issue management.

You are given an integer array prices representing the prices of various chocolates in a store. You are also given a single integer money, which represents your initial amount of money.

You must buy exactly two chocolates in such a way that you still have some non-negative leftover money. You would like to minimize the sum of the prices of the two chocolates you buy.

Return the amount of money you will have leftover after buying the two chocolates. If there is no way for you to buy two chocolates without ending up in debt, return money. Note that the leftover must be non-negative.

LeetCode Problem - 2706

import java.util.Arrays;

class Solution {

    // Method to calculate the remaining money after buying the two cheapest chocolates
    public int buyChoco(int[] prices, int money) {
        // Sort the array of prices to get the cheapest chocolates
        Arrays.sort(prices);

        // Calculate the total price of the two cheapest chocolates
        int priceOf1stTwoChocolates = prices[0] + prices[1];

        // Calculate the leftover money after buying the two chocolates
        int leftOver = money - priceOf1stTwoChocolates;

        // If not enough money to buy the two chocolates, return the original amount of money
        if (leftOver < 0) return money;

        // Return the leftover money
        return leftOver;
    }
}

More from this blog

S

Software and Performance Testing Insights

462 posts

Results-Driven Agile QA Specialist | Expert in Mobile & Web Testing | Proficient in Test Planning, Execution, and Root Cause Analysis.