O(1) Space and O(N) time explained solution


#1

Hope this will help:

int Solution::maxProfit(const vector &A) {
//An O(1) space and O(N) time solution

//Corner case when you have only day to transact
if(A.size()<=1)
    return 0;
    
//Have intial buy day as 0 and selling day as 1
int buy=0,sell=1;

int profit=0;
for(int sell=1;sell<A.size();sell++)
{
    if(A[buy]<A[sell])
        profit=max(profit,A[sell]-A[buy]);//Find the max profit
    else
        buy=sell;//If a stock is of lower price than what you buyed
        //Then you have a new potential buying stock
}
return profit;

}