Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Question link-https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
- //Answer code-
- class Solution {
- public:
- int maxProfit(vector<int>& prices) {
- int min_price=10000;
- int max_profit=0;
- for(int i=0;i<prices.size();i++)
- {
- //checking the min price while checking the max_profit it attains
- //to maximise the profit we search for the smallest element and using else if prevents elements greater that it
- //to come before
- if(prices[i]<min_price)
- {
- min_price=prices[i];
- }
- else if(prices[i]-min_price>max_profit)
- {
- max_profit=max(max_profit,prices[i]-min_price);
- }
- }
- return max_profit;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment