Skip to content

2144. Minimum Cost of Buying Candies With Discount 👍

  • Time: $O(\texttt{sort})$
  • Space: $O(\texttt{sort})$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
 public:
  int minimumCost(vector<int>& cost) {
    int ans = 0;

    ranges::sort(cost, [](const int a, const int b) { return a > b; });

    for (int i = 0; i < cost.size(); ++i)
      if (i % 3 != 2)
        ans += cost[i];

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
  public int minimumCost(int[] cost) {
    int ans = 0;

    cost = Arrays.stream(cost)
               .boxed()
               .sorted(Collections.reverseOrder())
               .mapToInt(Integer::intValue)
               .toArray();

    for (int i = 0; i < cost.length; ++i)
      if (i % 3 != 2)
        ans += cost[i];

    return ans;
  }
}
1
2
3
class Solution:
  def minimumCost(self, cost: List[int]) -> int:
    return sum(cost) - sum(sorted(cost)[-3::-3])