Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
01 public int maxProfit(int[] prices) {
02 if(prices.length<=1)
03 {
04 return 0;
05 }
06
07 int min=prices[0];
08 int max=prices[0];
09 int i=0;
10 int sum=0;
11
12 while(i<prices.length-1)
13 {
14 while(i<prices.length-1 && prices[i+1]<=prices[i])
15 {
16 i++;
17
18 }
19 min=prices[i];
20 max=prices[i];
21 while(i<prices.length-1 && prices[i+1]>=prices[i])
22 {
23 i++;
24 }
25 max=prices[i];
26 sum+=max-min;
27 min=prices[i];
28 }
29
30 return sum;
31 }
02 if(prices.length<=1)
03 {
04 return 0;
05 }
06
07 int min=prices[0];
08 int max=prices[0];
09 int i=0;
10 int sum=0;
11
12 while(i<prices.length-1)
13 {
14 while(i<prices.length-1 && prices[i+1]<=prices[i])
15 {
16 i++;
17
18 }
19 min=prices[i];
20 max=prices[i];
21 while(i<prices.length-1 && prices[i+1]>=prices[i])
22 {
23 i++;
24 }
25 max=prices[i];
26 sum+=max-min;
27 min=prices[i];
28 }
29
30 return sum;
31 }