Skip to content

Commit

Permalink
Create Best Time to Buy and Sell Stock
Browse files Browse the repository at this point in the history
First of all we take two integar as maximum profit whic is initially set to be zero and minimum so far which is the first element of the prices then we traverse and found the minimum between the minsofar and prices then we calculate the profit among them. then we find out the max between the maxprofit and calculated profit.
  • Loading branch information
Tusar7684 authored Jul 4, 2023
1 parent 8c599aa commit 8b758fe
Showing 1 changed file with 14 additions and 0 deletions.
14 changes: 14 additions & 0 deletions Best Time to Buy and Sell Stock
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
class Solution {
public:
int maxProfit(vector<int>& prices) {
int maxprofit=0;
int minsofar=prices[0];
int n= prices.size();
for(int i=0 ; i<n ; i++){
minsofar=min(minsofar,prices[i]);
int profit=prices[i]-minsofar;
maxprofit=max(maxprofit,profit);
}
return maxprofit;
}
};

0 comments on commit 8b758fe

Please sign in to comment.