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.
Solution: keep track of the current min value at each day. Subtract the price at each day with the current min value as the max. Update the value of max if the difference is larger than max.
Solution: keep track of the current min value at each day. Subtract the price at each day with the current min value as the max. Update the value of max if the difference is larger than max.
01 public int maxProfit(int[] prices) {
02 if(prices.length<=1)
03 {
04 return 0;
05 }
06 int min=prices[0];
07 int max=0;
08 for(int i=1;i<prices.length;i++)
09 {
10 if(prices[i]<min)
11 {
12 min=prices[i];
13 }
14
15 int diff=prices[i]-min;
16 if(diff>max)
17 {
18 max=diff;
19 }
20 }
21 return max;
22 }
02 if(prices.length<=1)
03 {
04 return 0;
05 }
06 int min=prices[0];
07 int max=0;
08 for(int i=1;i<prices.length;i++)
09 {
10 if(prices[i]<min)
11 {
12 min=prices[i];
13 }
14
15 int diff=prices[i]-min;
16 if(diff>max)
17 {
18 max=diff;
19 }
20 }
21 return max;
22 }
没有评论:
发表评论