Minimum Cost of Buying Candies With Discount
给一个数组, 是东西的价格, 可以买二送一, 求花费. 要求送的cost比买的要少.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
class Solution { public int minimumCost(int[] cost) { Arrays.sort(cost); if(cost.length == 1) return cost[0]; if(cost.length == 2) return cost[0] + cost[1]; int res = 0; int i = cost.length - 1; while(i >= 0){ if(i == 0){ res += cost[i]; break; }else if(i == 1){ res += cost[i]; res += cost[i - 1]; break; }else{ res += cost[i]; res += cost[i - 1]; i -= 3; } } return res; } } |