Simple O(n) and O(1) space solution with comments


#1

int Solution::maxProfit(const vector &A) {

int n=A.size();    
if(n==0)
  return 0;
int localMin=A[0];   //Local min stores the min value of share till now.

int res=0;  //this stores the result
for(int i=1;i<n;i++)
{
    localMin=min(localMin,A[i]);   //here we check if this stock price at ith index is min or not
    res=max(res,A[i]-localMin);   //if we decide to sell this stock at this day then we get max profit when we subtract  from min stock price day till date(which is stored in localMin var.)
}

return res;

}