Skip to content

Commit ca6a083

Browse files
Create BestTimeToBuyStocks.cpp
1 parent c5c05c2 commit ca6a083

1 file changed

Lines changed: 21 additions & 0 deletions

File tree

‎BestTimeToBuyStocks.cpp‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/* Say you have an array for which the ith element is the price of a given stock on day i.
2+
3+
If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.
4+
5+
Note that you cannot sell a stock before you buy one. */
6+
7+
8+
class Solution {
9+
public:
10+
int maxProfit(vector<int>& v) {
11+
int profit=0;
12+
int mini=INT_MAX;
13+
for(int i=0;i<v.size();i++){
14+
mini=min(mini,v[i]);
15+
profit=max(profit,(v[i]-mini));
16+
}
17+
return profit;
18+
}
19+
20+
21+
};

0 commit comments

Comments
 (0)