Minimum Cost of Buying Candies With Discount LeetCode solution in C++

1
// Solution 01:
2
class Solution {
3
public:
4
int minimumCost(vector<int> &cost) {
5
int n = cost.size();
6
int i = n - 1, ans = 0;
7

8
if (n <= 2) {
9
for (auto x : cost) ans += x;
10
return ans;
11
}
12

13
sort(cost.begin(), cost.end());
14

15
while (i >= 1) {
16
ans += cost[i] + cost[i - 1];
17
if (i - 1 == 0 || i - 1 == 1) return ans;
18
i = i - 3;
19
}
20
ans += cost[0];
21

22
return ans;
23
}
24
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0