코딩테스트 풀이/JAVA
[LeetCode/Easy] 2706. Buy Two Chocolates
무지맘
2023. 6. 30. 21:42
1. Input
1) int[] prices
2) int money
2. Output
1) money를 넘기지 않는 선에서 초콜릿 2개를 사려고 한다. 이때 초콜릿 2개의 가격의 합은 최소로 한다고 할 때, money를 내고 초콜릿을 사고 난 거스름돈을 반환
2) 만약 초콜릿의 가격이 money를 초과한다면 money를 반환
3. Constraint
1) 2 <= prices.length <= 50
2) 1 <= prices[i] <= 100
3) 1 <= money <= 100
4. Example
Input: prices = [1,2,2], money = 3 -> Output: 0
Input: prices = [3,2,3], money = 3 -> Output: 3
5. Code
1) 첫 코
class Solution {
public int buyChoco(int[] prices, int money) {
Arrays.sort(prices);
return prices[0]+prices[1]>money ? money : money-prices[0]-prices[1];
}
}
- 70%, 9%
2) sort를 쓰지 않고 다시 풀어본 코드
class Solution {
public int buyChoco(int[] prices, int money) {
int c1 = Math.min(prices[0], prices[1]), c2 = Math.max(prices[0], prices[1]);
for(int i=2 ; i<prices.length ; i++){
if(prices[i]<c1){
c2 = c1;
c1 = prices[i];
} else if(prices[i]<c2)
c2 = prices[i];
}
return c1+c2 > money ? money : money - c1 - c2;
}
}
- 100%, 67%
- 역시 sort가 시간이 많이 걸린다.