//买卖股票的最佳时机 II
public class Stock
{
// 方法1
public static int calculate(int prices[], int s)
{
if (s >= prices.length)
return 0;
int max = 0;
for (int start = s; start < prices.length; start++)
{
int maxprofit = 0;
for (int i = start + 1; i < prices.length; i++)
{
if (prices[start] < prices[i])
{
int profit = calculate(prices, i + 1) + prices[i]
- prices[start];
if (profit > maxprofit)
maxprofit = profit;
}
}
if (maxprofit > max)
max = maxprofit;
}
return max;
}
public static int maxProfit1(int[] prices)
{
return calculate(prices, 0);
}
// 方法2——简单
public static int maxProfit2(int[] prices)
{
int maxprofit = 0;
for (int i = 1; i < prices.length; i++)
{
if (prices[i] > prices[i - 1])
maxprofit += prices[i] - prices[i - 1];
}
return maxprofit;
}
// 方法3
public static int maxProfit4(int[] prices)
{
int i = 0;
int valley = prices[0];
int peak = prices[0];
int maxprofit = 0;
while (i < prices.length - 1)
{
// 股票下跌,当前值大于下一个值,说明股票在下降,当前i不大于下一个值i+1的时候,i买入最小值
while (i < prices.length - 1 && prices[i] >= prices[i + 1])
{
i++;
}
valley = prices[i]; // 股票最小值买入
// 股票上涨的最大值,当前值i小于下一个值i+1,说明股票在上涨,当i大于i+1的时候,i卖出最大值
while (i < prices.length - 1 && prices[i] <= prices[i + 1])
{
i++;
}
peak = prices[i];// 股票上涨的最大值卖出
maxprofit += peak - valley;
}
return maxprofit;
}
public static void main(String[] args)
{
int[] prices = { 7, 1, 5, 3, 6, 4 };
int[] prices1 = { 1, 2, 3, 4, 5 };
int[] prices2 = { 7, 6, 4, 3, 1 };
int[] prices3 = { 7, 6, 8, 3, 5, 6, 1 };
// System.out.println(maxProfit2(prices));
// System.out.println(maxProfit2(prices1));
// System.out.println(maxProfit2(prices2));
System.out.println(maxProfit4(prices3));
}
}
// 方法2 简单处理