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 }
Hi, if we only care about the total profit, we can adds to the profit whenever we notice that current price p[i] is higher than previous price p[i-1]. :)
回复删除Hi,这道问题其实没有这么简单。因为你考虑的是固定大小的数组。如果给你的是个data stream,就不能这么做。我觉得用priority queue实现heap sort会比较好
回复删除