122. best time to buy and sell stock ii 解答

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

解答

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
public class Solution {
public static void main(String[] args) {
int[] demo = {1,2,4};
System.out.println(maxProfit(demo));
}
public static int maxProfit(int[] prices) {
return maxtemp(prices,0,0);
}
static int maxtemp(int[]prices,int start,int max) {
if(prices.length < 2){
return 0;
}
if(start>prices.length-2){
return 0;
}
int mintemp = start;
for(int i = start;i<prices.length;i++) {
if(prices[i]>prices[start]){
break;
}
if(i == prices.length-1&&prices[i]<prices[start]){
return 0;
}
if(i == prices.length-1){
break;
}
if(prices[i]<prices[start]&&prices[i]<prices[i+1]) {
mintemp = i;
break;
}
}
int maxtemp = mintemp+1;
for(int i = maxtemp;i<prices.length;i++) {
if(i == prices.length-1){
if(prices[i]>prices[maxtemp]) {
maxtemp = i;
break;
}
break;
}
if(prices[i]<prices[maxtemp]) {
break;
}
if(prices[i]>prices[maxtemp]&&prices[i]>prices[i+1]) {
maxtemp = i;
break;
}
}
return max += prices[maxtemp]-prices[mintemp]+maxtemp(prices,maxtemp+1,max);
}
}