Skip to content

Commit 3349bde

Browse files
committed
feat: best time to by and sell stock
1 parent edddfe9 commit 3349bde

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/**
2+
* 121. Best Time to Buy and Sell Stock
3+
* 반복문 돌면서 가장 작은 값을 기억해둡니다
4+
* 매번 최소값과의 차이를 비교합니다
5+
*/
6+
class Solution {
7+
public int maxProfit(int[] prices) {
8+
int maxProfit = 0;
9+
int minPrice = Integer.MAX_VALUE;
10+
11+
for (int price: prices) {
12+
if (price < minPrice) { // 최소 값 찾기
13+
minPrice = price;
14+
}
15+
if (price - minPrice > maxProfit) {
16+
maxProfit = price - minPrice;
17+
}
18+
}
19+
return maxProfit;
20+
}
21+
}

0 commit comments

Comments
 (0)