class Solution {
public int maxProfit(int[] prices) {
int small = prices[0];
int big = 0;
int max = 0;
for (int i = 1; i < prices.length; i++) {
if (prices[i] < small) {
small = prices[i];
big = 0;
} else {
big = prices[i];
}
if (max < big - small) {
max = big - small;
}
}
return max;
}
}
이거 Easy라고?? 자괴감 든다….
아무 생각없이 n^n 로 풀었다가 런타임 에러나서
map 만들고 별짓 다해봤는데
난이도는 Easy라니까 맵까지는 안쓸것같고
점점 산으로가다가 결국 클로드한테 힌트만 달라고 했다.
힌트 내용


힌트도 정말 잘준다 AI..
힌트를 보자마자 5분만에 풀어버렸다
1시간 내로 못풀겠으면 힌트라도 받자 앞으로…
form Ai
small (최솟값), big (현재 가격), max (최대 이익)big// ❌ 현재 코드
if (prices[i] < small) {
small = prices[i];
big = 0; // 불필요한 재설정
} else {
big = prices[i];
}
max = Math.max(max, big - small);
// ✔ 개선
max = Math.max(max, prices[i] - small);
// big 변수 없이 직접 계산 가능
big = 0 설정의 의미 불명확if (prices[i] < small) {
small = prices[i];
big = 0; // 왜 0으로?
}
big을 0으로 설정하는 것은 논리적으로 혼란스러움big 변수 자체가 불필요// 현재
int small, big, max
// 더 명확하게
int minPrice, currentPrice, maxProfit
// 또는
int lowestBuy, maxProfit
class Solution {
public int maxProfit(int[] prices) {
int minPrice = prices[0];
int maxProfit = 0;
for (int i = 1; i < prices.length; i++) {
minPrice = Math.min(minPrice, prices[i]);
maxProfit = Math.max(maxProfit, prices[i] - minPrice);
}
return maxProfit;
}
}
변경사항:
big 변수 제거Math.min(), Math.max() 활용class Solution {
public int maxProfit(int[] prices) {
int minPrice = Integer.MAX_VALUE;
int maxProfit = 0;
for (int price : prices) {
minPrice = Math.min(minPrice, price);
maxProfit = Math.max(maxProfit, price - minPrice);
}
return maxProfit;
}
}
장점:
prices[0] 초기화 불필요class Solution {
public int maxProfit(int[] prices) {
int maxProfit = 0;
int minPrice = prices[0];
for (int price : prices) {
// 오늘 팔면 얼마 벌까?
int profit = price - minPrice;
maxProfit = Math.max(maxProfit, profit);
// 더 싼 날이 있으면 갱신
minPrice = Math.min(minPrice, price);
}
return maxProfit;
}
}
| 방법 | 시간복잡도 | 공간복잡도 | 코드 길이 | 가독성 |
|---|---|---|---|---|
| 내 코드 | O(n) | O(1) | 15줄 | 보통 |
| 방법 1 | O(n) | O(1) | 10줄 | 좋음 ⭐ |
| 방법 2 | O(n) | O(1) | 10줄 | 매우 좋음 |
| 방법 3 | O(n) | O(1) | 12줄 | 좋음 |
Greedy 알고리즘
불필요한 변수 제거
big 변수는 중간 계산용Math 함수 활용
Math.min(), Math.max() 사용Dynamic Programming 관점
문제의 본질:
최대 이익 = max(현재 가격 - 지금까지 최저 가격)
왜 이렇게 풀 수 있나?
class Solution {
public int maxProfit(int[] prices) {
int minPrice = prices[0];
int maxProfit = 0;
for (int i = 1; i < prices.length; i++) {
// 더 싼 날이 있으면 갱신
minPrice = Math.min(minPrice, prices[i]);
// 오늘 팔면 얼마 벌까?
maxProfit = Math.max(maxProfit, prices[i] - minPrice);
}
return maxProfit;
}
}
개선 사항:
big 변수 제거 (33% 코드 감소)dp[i] = i번째 날까지의 최대 이익dp[i] = max(dp[i-1], prices[i] - minPrice)LeetCode 122: Best Time to Buy and Sell Stock II (Medium)
LeetCode 123: Best Time to Buy and Sell Stock III (Hard)
LeetCode 188: Best Time to Buy and Sell Stock IV (Hard)
LeetCode 309: Best Time to Buy and Sell Stock with Cooldown (Medium)
LeetCode 53: Maximum Subarray (Medium)
class Solution {
public int maxProfit(int[] prices) {
int[] minPrice = {Integer.MAX_VALUE};
int[] maxProfit = {0};
Arrays.stream(prices).forEach(price -> {
minPrice[0] = Math.min(minPrice[0], price);
maxProfit[0] = Math.max(maxProfit[0], price - minPrice[0]);
});
return maxProfit[0];
}
}
주의: 가독성은 떨어지고 성능도 느림. 실전에서는 비추천!
#LeetCode #Greedy #DynamicProgramming #알고리즘 #코딩테스트 #Java
#Easy #배열순회 #최적화