最佳股票交易时机

来源:互联网 发布:阿里云 aws对比 编辑:程序博客网 时间:2024/05/17 04:52

第i天无非两种情况:买、卖
buy[i]:第i天买股票的最大收益;
sell[i]:第i天卖股票的最大收益;

初始状态:

buy[0] = -price[0];sell[0] = 0;

状态转移方程:

buy[i] = max(buy[i-1],sell[i-1]-price[i]);sell[i] = max(sell[i-1],buy[i-1]+price[i]-fee);

代码:

public int maxProfit(int[] prices, int fee) {    int buy = -prices[0], sell = 0;    for(int i = 1;i<prices.length;i++){        buy = Math.max(buy,sell - prices[i-1]);        sell = Math.max(sell, buy + prices[i] - fee);    }    return sell;}