Skip to content

Commit a63d945

Browse files
committed
best time to buy and sell stock
1 parent 5f080b5 commit a63d945

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* Runtime: 1ms
3+
* Time Complexity: O(n)
4+
*
5+
* Memory: 94.08MB
6+
* Space Complexity: O(1)
7+
*
8+
* Approach: 그리디 알고리즘
9+
* - 주어진 prices 배열을 순회하며 최소 가격(min)을 갱신
10+
*/
11+
class Solution {
12+
public int maxProfit(int[] prices) {
13+
int maxProfit = 0;
14+
int min = prices[0];
15+
16+
for (int i=1; i<prices.length; i++) {
17+
if (min >= prices[i]) {
18+
min = prices[i];
19+
} else {
20+
maxProfit = Math.max(maxProfit, prices[i]-min);
21+
}
22+
}
23+
24+
return maxProfit;
25+
}
26+
}

0 commit comments

Comments
 (0)