Skip to content

Commit 2c309ba

Browse files
Create 2706-buy-two-chocolates.java
1 parent 52caeef commit 2c309ba

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

java/2706-buy-two-chocolates.java

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/*------------------------------
2+
Time Complexity: O(n)
3+
Space Complexity: O(1)
4+
-------------------------------*/
5+
class Solution {
6+
public int buyChoco(int[] prices, int money) {
7+
int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE;
8+
9+
for(int p: prices){
10+
if(p < min2){
11+
if(p < min1){
12+
min2 = min1;
13+
min1 = p;
14+
}
15+
else
16+
min2 = p;
17+
}
18+
}
19+
int leftover = money - (min1 + min2);
20+
return (leftover < 0)? money: leftover;
21+
}
22+
}
23+
24+
/*------------------------------
25+
Time Complexity: O(nlog(n))
26+
Space Complexity: O(1)
27+
-------------------------------*/
28+
class Solution {
29+
public int buyChoco(int[] prices, int money) {
30+
Arrays.sort(prices);
31+
int leftover = money - (prices[0] + prices[1]);
32+
return (leftover < 0)? money : leftover;
33+
}
34+
}

0 commit comments

Comments
 (0)