Skip to content

2706. Buy Two Chocolates 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
 public:
  int buyChoco(vector<int>& prices, int money) {
    int min1 = INT_MAX;
    int min2 = INT_MAX;

    for (const int price : prices)
      if (price <= min1) {
        min2 = min1;
        min1 = price;
      } else if (price < min2) {
        min2 = price;
      }

    const int minCost = min1 + min2;
    return minCost > money ? money : money - minCost;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
  public int buyChoco(int[] prices, int money) {
    int min1 = Integer.MAX_VALUE;
    int min2 = Integer.MAX_VALUE;

    for (final int price : prices)
      if (price <= min1) {
        min2 = min1;
        min1 = price;
      } else if (price < min2) {
        min2 = price;
      }

    final int minCost = min1 + min2;
    return minCost > money ? money : money - minCost;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
  def buyChoco(self, prices: list[int], money: int) -> int:
    min1 = math.inf
    min2 = math.inf

    for price in prices:
      if price <= min1:
        min2 = min1
        min1 = price
      elif price < min2:
        min2 = price

    minCost = min1 + min2
    return money if minCost > money else money - minCost