75-days-dsa-challenge

Ninja technique🥷 to ACE DSA Interviews.

View the Project on GitHub

121. Best Time to Buy and Sell Stock (Easy)

O(N^2) Time and O(1) Space

Code

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int n = prices.size();
        int maxProfit=0;

        for(int i=0;i<n;i++){
            for(int j=i+1;j<n;j++){
                maxProfit=max(maxProfit,prices[j]-prices[i]);
            }
        }
        return maxProfit;
    }
};

O(N) Time and O(N) Space

Code

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int n = prices.size();
        int maxProfit = 0;
        vector<int> futureMax(n);
        futureMax[n-1] = prices[n-1];
        for(int i=n-2; i>=0; i--) {
            futureMax[i] = max(prices[i], futureMax[i + 1]);
        }
        for(int i=0; i<n; i++) {
            maxProfit = max(maxProfit, futureMax[i] - prices[i]);
        }
        return maxProfit;
    }
};

O(N) Time and O(1) Space

Code

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int n = prices.size();
        int maxProfit=0,minStockPrice=1e9;
        for(int i=0;i<n;i++){
            maxProfit=max(maxProfit,prices[i]-minStockPrice);
            minStockPrice=min(minStockPrice,prices[i]);
        }
        return maxProfit;
    }
};

The inner for loop can be optimized and will require 33% less time.

Code

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int n = prices.size();
        int maxProfit=0,minStockPrice=1e9;
        for(int i=0;i<n;i++){ // 33% faster
            if(minStockPrice>prices[i])
                minStockPrice=prices[i];
            else
                maxProfit=max(maxProfit,prices[i]-minStockPrice);
        }
        return maxProfit;
    }
};