Skip to content

Commit 6a946cd

Browse files
authored
Create 121.cpp
Best Time to Buy and Sell Stock
1 parent 66b5e52 commit 6a946cd

File tree

1 file changed

+21
-0
lines changed
  • leetcode/cpp/dynamic programming

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+
//Best Time to Buy and Sell Stock
2+
3+
class Solution {
4+
public:
5+
int maxProfit(vector<int>& prices) {
6+
if(prices.size()==0){
7+
return 0;
8+
}
9+
int buy=prices[0];
10+
int ans=0;
11+
for(int i=0;i<prices.size();i++){
12+
if(prices[i]<buy){
13+
buy=prices[i];
14+
}
15+
else if(prices[i]-buy>ans){
16+
ans=prices[i]-buy;
17+
}
18+
}
19+
return ans;
20+
}
21+
};

0 commit comments

Comments
 (0)