2706. Buy Two Chocolates

Sorting

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public int buyChoco(int[] prices, int money) {
Arrays.sort(prices);
int leftMoney = money - prices[0] - prices[1];
if (leftMoney < 0) {
return money;
} else {
return leftMoney;
}
}
}

Traverse

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public int buyChoco(int[] prices, int money) {
int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE;
for (int price : prices) {
if (price < min1) {
min2 = min1; // 注意需要将 min1 赋值给 min2, 防止 min1 丢失,可用如下数组复现:[69, 91, 78, 19, 40, 13]
min1 = price;
} else if (price < min2) {
min2 = price;
}
}

int leftMoney = money - min2 - min1;
if (leftMoney < 0) {
return money;
} else {
return leftMoney;
}
}
}

References

2706. Buy Two Chocolates