Can be solved with a stack in linear time


#1

Comment body goes here.


#2

Doesn’t even need a stack !
#define ll long int
int Solution::maxProfit(const vector &A) {
int n=A.size();
if(n<=1)
return 0;
long int mv=0,mi=A[0],mx=0;
for(int i=1;i<n;i++){
mi=min(mi,(ll)A[i-1]);
mv=max(mv,A[i]-mi);
}
return mv;
}