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
public class Solution {
public int maxProfit(int[] prices) {
int lirun = 0;
int money = 0;
int price = 0;
boolean buy = true;
if(prices.length==0||prices.length==1){
return 0;
}
if(prices[0]<prices[1]){
money=-prices[0];
buy=false;
}
for(int i=1;i<prices.length;i++){
boolean cz = t(i,prices,buy);
if(cz){
if(buy){
money = money - prices[i];
price = prices[i];
buy = false;
}else{
money = money + prices[i];
price = 0;
buy = true;
}
}
}
return money;
}
public boolean t(int i,int[] prices,boolean buy){
if(buy){
if(i>=prices.length-1){
return false;
}
if(prices[i]<prices[i+1]){
return true;
}
return false;
}else{
if(i>=prices.length-1){
return true;
}else if(prices[i]>prices[i+1]){
return true;
}
return false;
}
}
}