Skip to content

Commit e54fa8d

Browse files
committed
Best Time to Buy and Sell Stock
1 parent db549e2 commit e54fa8d

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

problem55/main.dart

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
2+
//122. Best Time to Buy and Sell Stock
3+
import 'dart:math';
4+
5+
void main(List<String> args) {
6+
print(maxProfit([7,6,4,3,1]));
7+
}
8+
9+
int maxProfit(List<int> prices) {
10+
int profit=0;
11+
int buy=0;
12+
int sell=1;
13+
14+
while(sell<prices.length){
15+
if(prices[buy]<prices[sell]){
16+
var calculate=prices[sell]-prices[buy];
17+
profit=max(calculate, profit);
18+
}else{
19+
buy=sell;
20+
}
21+
sell++;
22+
}
23+
return profit;
24+
}

0 commit comments

Comments
 (0)