jayati

Untitled

Sep 1st, 2022
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.82 KB | None | 0 0
  1. //Question link-https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
  2.  
  3. //Answer code-
  4. class Solution {
  5. public:
  6. int maxProfit(vector<int>& prices) {
  7. int min_price=10000;
  8. int max_profit=0;
  9. for(int i=0;i<prices.size();i++)
  10. {
  11. //checking the min price while checking the max_profit it attains
  12. //to maximise the profit we search for the smallest element and using else if prevents elements greater that it
  13. //to come before
  14. if(prices[i]<min_price)
  15. {
  16. min_price=prices[i];
  17. }
  18. else if(prices[i]-min_price>max_profit)
  19. {
  20. max_profit=max(max_profit,prices[i]-min_price);
  21. }
  22. }
  23. return max_profit;
  24. }
  25. };
Tags: Question 2
Advertisement
Add Comment
Please, Sign In to add comment