Minimum Cost of Buying Candies With Discount LeetCode solution in Java

1
class Solution {
2
/**
3
* Algorithm 1. Sort the cost array. 2. In a loop, start from the back and buy items n, n-1 to get
4
* 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
*/
7
public int minimumCost(int[] cost) {
8
int minCost = 0;
9
int index = cost.length - 1;
10
Arrays.sort(cost);
11
// add items in pairs of 2, the 3rd one getting it for free.
12
while (index > 1) {
13
minCost += cost[index] + cost[index - 1];
14
index -= 3;
15
}
16
// add the remaining 1, 2 items, if any.
17
while (index >= 0) {
18
minCost += cost[index--];
19
}
20
return minCost;
21
}
22
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0