DEV Community

Mayank Arora
Mayank Arora

Posted on

121. Best Time to Buy and Sell Stock [Leetcode][C++]

All suggestions are welcome. Please upvote if you like it. Thank you.


Leetcode Problem Link: 121. Best Time to Buy and Sell Stock


Brute Force Solution:

class Solution {
public:
    int maxProfit(vector<int>& prices) { 
    // Brute Force Solution Time O(N^2) & Auxiliary Space O(1)
    int len=prices.size(),profit=0;
        for(int i=0;i<len;i++){
            for(int j=i+1;j<len;j++){
                if(prices[j]>prices[i]){
                    int pro=prices[j]-prices[i];
                    profit=max(profit,pro);
                }
            }
        }
    return profit; 
  }
};

Enter fullscreen mode Exit fullscreen mode

Efficient Solution:

class Solution {
public:
    int maxProfit(vector<int>& prices) {
    // Efficient Solution Time O(N) & Auxiliary Space O(1)
    int min_val=INT_MAX,profit=0,len=prices.size();
    for(int i=0;i<len;i++){
          min_val=min(min_val,prices[i]);
          profit=max(profit,prices[i]-min_val);
        }
    return profit;
    }
};

Enter fullscreen mode Exit fullscreen mode

All suggestions are welcome. Please upvote if you like it. Thank you.

Top comments (0)