LC.P2706[购买两块巧克力]

方法一:一次遍历

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public int buyChoco(int[] prices, int money) {
int a = Integer.MAX_VALUE, b = Integer.MAX_VALUE;
for (int x : prices) {
if (x < a) {
b = a;
a = x;
} else if (x < b) {
b = x;
}
}
int cost = a + b;
return money < cost ? money : money - cost;
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(1)$