Minimum Cost of Buying Candies With Discount LeetCode solution in Java
1class Solution {2/**3* Algorithm 1. Sort the cost array. 2. In a loop, start from the back and buy items n, n-1 to get4* n-2 for free. 3. Decrement the position by 3 and continue. stop when you reach 1. 4. From 1,5* add the remaining 1 or 2 items.6*/7public int minimumCost(int[] cost) {8int minCost = 0;9int index = cost.length - 1;10Arrays.sort(cost);11// add items in pairs of 2, the 3rd one getting it for free.12while (index > 1) {13minCost += cost[index] + cost[index - 1];14index -= 3;15}16// add the remaining 1, 2 items, if any.17while (index >= 0) {18minCost += cost[index--];19}20return minCost;21}22}