How to maximize the profit
Counter example

Consider the array $A=[5,2,3,4,1]$, where $n=5$.

(i) Then $A[1]=5$ is the maximum and $x=1$, $A[5]=1$ is the minimum and $y=5$.

(ii) And find minimum in $A[1 .. x] = A[1 .. 1]=A[1]$ which is $5$. So, $u=1$.

(iii) Find maximum in $A[y..n] = A[5..5]= A[5]$ which is $1$. So, $v=5$.

(iv)  Answer is $$\max(A[x]-A[u]),(A[v]-A[y]) = \max(A[1]-A[1], A[5]- A[5])= \max(0,0)=0$$ 

But the maximum profit is $A[4] - A[2] = 2$.

$O(n)$ solution

The idea is to start with two pointers $i=1$ and $j=2$ and at each step increase $j$ by one. At each step check if the difference $A[j] - A[j]$ is greater than the maximum profit. If it is then update the maximum profit. But if $A[i] &gt; A[j]$ (in which case $A[j] - A[j]$ is negative and max profit is not updated) then we make $i$ point to the same location $j$ points to, since if for some $k &gt; j$, $A[k] - A[i]$ is greater than the current maximum profit then $A[k] - A[j] &gt; A[k] - A[i] &gt; maxprofit$.  


Set $i=1$, $j=2$, $maxprofit=0$
If $A[j] - A[i] &gt; maxprofit$ then set $maxprofit = A[j] - A[i]$
If $A[i] &gt; A[j]$ then set $i = j$
$j = j + 1$
If $j&gt;n$ return $maxprofit$
Goto 2