算法题:买卖股票的最佳时机(只能有一次买卖,可以最多两次买卖,不限次数)
LeetCode——Best Time to Buy and Sell Stock III
package src.main.java;
public class test {
//买卖一次
public int maxProfit(int[] prices) {
if(prices==null || prices.length==0)
return 0;
int local = 0;
int global = 0;
for(int i=0;i<prices.length-1;i++)
{
//计算两天股票的差。
int diff = prices[i+1]-prices[i];
// 计算局部最大涨幅。在local+diff与0中取最大值其目的是:出现大跌,即local+diff为负,
// 此时如果直接赋值给local会出现local为负的情况,股票再涨的时候local+diff计算的就不是计算涨幅了。
local = Math.max(local+diff,0);
//记录股票全局最大涨幅
global = Math.max(local, global);
}
return global;
}
//不限次数
public int maxProfit_II(int[] prices) {
if (prices == null || prices.length == 0)
return 0;
int res = 0;
for (int i = 0; i < prices.length - 1; i++) {
//计算两天股票的差。
int diff = prices[i + 1] - prices[i];
//凡是两天股票差大于零的情况,都买入。
if (diff > 0)
res += diff;
}
return res;
}
//可以最多两次买卖;或者买卖K次
public int maxProfit_III(int[] prices) {
if(prices==null || prices.length==0)
return 0;
int[] local = new int[3];
int[] global = new int[3];
for(int i=0;i<prices.length-1;i++)
{
int diff = prices[i+1]-prices[i];
for(int j=2;j>=1;j--)
{
local[j] = Math.max(global[j-1]+(diff>0?diff:0), local[j]+diff);
global[j] = Math.max(local[j],global[j]);
}
}
return global[2];
}
public static void main (String[] arg){
test test = new test();
int prices [] = {1,3,5,7,9,-10,-22,-35};
System.out.println(test.maxProfit(prices));
}
}