java.lang.Object
g2101_2200.s2144_minimum_cost_of_buying_candies_with_discount.Solution

public class Solution extends Object
2144 - Minimum Cost of Buying Candies With Discount.<p>Easy</p> <p>A shop is selling candies at a discount. For <strong>every two</strong> candies sold, the shop gives a <strong>third</strong> candy for <strong>free</strong>.</p> <p>The customer can choose <strong>any</strong> candy to take away for free as long as the cost of the chosen candy is less than or equal to the <strong>minimum</strong> cost of the two candies bought.</p> <ul> <li>For example, if there are <code>4</code> candies with costs <code>1</code>, <code>2</code>, <code>3</code>, and <code>4</code>, and the customer buys candies with costs <code>2</code> and <code>3</code>, they can take the candy with cost <code>1</code> for free, but not the candy with cost <code>4</code>.</li> </ul> <p>Given a <strong>0-indexed</strong> integer array <code>cost</code>, where <code>cost[i]</code> denotes the cost of the <code>i<sup>th</sup></code> candy, return <em>the <strong>minimum cost</strong> of buying <strong>all</strong> the candies</em>.</p> <p><strong>Example 1:</strong></p> <p><strong>Input:</strong> cost = [1,2,3]</p> <p><strong>Output:</strong> 5</p> <p><strong>Explanation:</strong> We buy the candies with costs 2 and 3, and take the candy with cost 1 for free.</p> <p>The total cost of buying all candies is 2 + 3 = 5. This is the <strong>only</strong> way we can buy the candies.</p> <p>Note that we cannot buy candies with costs 1 and 3, and then take the candy with cost 2 for free.</p> <p>The cost of the free candy has to be less than or equal to the minimum cost of the purchased candies.</p> <p><strong>Example 2:</strong></p> <p><strong>Input:</strong> cost = [6,5,7,9,2,2]</p> <p><strong>Output:</strong> 23</p> <p><strong>Explanation:</strong> The way in which we can get the minimum cost is described below:</p> <ul> <li> <p>Buy candies with costs 9 and 7</p> </li> <li> <p>Take the candy with cost 6 for free</p> </li> <li> <p>We buy candies with costs 5 and 2</p> </li> <li> <p>Take the last remaining candy with cost 2 for free</p> </li> </ul> <p>Hence, the minimum cost to buy all candies is 9 + 7 + 5 + 2 = 23.</p> <p><strong>Example 3:</strong></p> <p><strong>Input:</strong> cost = [5,5]</p> <p><strong>Output:</strong> 10</p> <p><strong>Explanation:</strong> Since there are only 2 candies, we buy both of them. There is not a third candy we can take for free.</p> <p>Hence, the minimum cost to buy all candies is 5 + 5 = 10.</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 <= cost.length <= 100</code></li> <li><code>1 <= cost[i] <= 100</code></li> </ul>
  • Constructor Details

    • Solution

      public Solution()
  • Method Details

    • minimumCost

      public int minimumCost(int[] cost)