Skip to content

Commit 802ddd7

Browse files
committed
add solution for best time to buy and sell stock
1 parent 514a084 commit 802ddd7

1 file changed

Lines changed: 41 additions & 0 deletions

File tree

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
class Solution {
2+
3+
4+
5+
6+
7+
//O(n)에 증가 한 경우 profitMax를 갱신시키며 판단 -> time limit
8+
public int maxProfit(int[] prices) {
9+
int profitMax = 0;
10+
/*
11+
for(int i=0; i< prices.length - 1; i++){
12+
int buy= prices[i];
13+
14+
15+
for(int d =i+1; d < prices.length; d++){
16+
int sellCandid = prices[d];
17+
if (sellCandid - buy > profitMax){
18+
profitMax = sellCandid - buy;
19+
}
20+
21+
}
22+
}//end of for
23+
24+
*/
25+
26+
int priceMin = Integer.MAX_VALUE;
27+
for(int i =0; i < prices.length; i++){
28+
if (prices[i] < priceMin){
29+
priceMin = prices[i];
30+
}
31+
else{
32+
profitMax = Math.max(profitMax, prices[i] - priceMin);
33+
}
34+
}
35+
36+
return profitMax;
37+
38+
}
39+
40+
}
41+

0 commit comments

Comments
 (0)