美文网首页
动态规划 买股票

动态规划 买股票

作者: b8dfe6f70d0b | 来源:发表于2017-04-27 10:26 被阅读0次

T+2规则

本题意为用户在卖出之后需要休息一天才能进行操作,那么在本题中用户是存在有三个状态,未持有(unhold)、持有(hold)、休息(cooldown)这三种,这三种状态的状态转化图为:

其对应的状态转换函数为:

unhold[i] = max(unhold[i - 1], cooldown[i - 1]); // Stay at s0, or rest from s2

hold[i] = max(hold[i - 1], unhold[i - 1] - prices[i]); // Stay at s1, or buy from s0

cooldown[i] = hol[i - 1] + prices[i]; // Only one way from s1

代码为:

package wx.algorithm.op.dp.stock;

/**

* Created by apple on 16/8/21.

*/

public class StockWithCoolDown {

public int maxProfit(int[] prices) {

//判断日期长度是否大于1

if (prices.length <= 1) {

return 0;

}

//构建三个状态数组

int[] unhold = new int[prices.length];

int[] hold = new int[prices.length];

int[] cooldown = new int[prices.length];

unhold[0] = 0;

hold[0] = -prices[0];

cooldown[0] = Integer.MIN_VALUE;

for (int i = 1; i < prices.length; i++) {

unhold[i] = Math.max(unhold[i - 1], cooldown[i - 1]);

hold[i] = Math.max(hold[i - 1], unhold[i - 1] - prices[i]);

cooldown[i] = hold[i - 1] + prices[i];

}

return Math.max(unhold[prices.length - 1],cooldown[prices.length - 1]);

}

}

相关文章

  • 动态规划 买股票

    T+2规则 本题意为用户在卖出之后需要休息一天才能进行操作,那么在本题中用户是存在有三个状态,未持有(unhold...

  • 动态规划5:买股票问题

    7天内价格走势如下[7, 1, 5, 3, 6, 4]。 注明: 1次交易: 买+卖算一次,但必须先买入再卖出,且...

  • 动态规划实例分析-买股票问题

    我被伤害了,在看到那几行代码的时候,我的眼眶开始发热,我的脑子开始不清醒,我是谁,我为什么会在这儿,我为什么这么菜...

  • 2022-02-19 动态规划高频题专题【1】

    动态规划基本类型 dp基础 背包问题 打家劫舍 股票问题 子序列问题 进阶动态规划 深入理解动态规划过程 定义dp...

  • 动态规划——买股票的最佳时期

    买股票的最佳时期,是一道经典的动态规划题目,在leetcode中有很多题目。今天通过一个通用的dp推导公式解决所有...

  • 【Leetcode】【Python】121. Best Time

    问题描述:股票买进卖出问题 代码示例:动态规划

  • 炒股历险记

    题目感觉挺通俗的,买股票的风险比较高,时间长了,对涨跌心态更平静了。 买股票就是买大家对股票的信心,信心是动态的,...

  • 求最大子数组(贪心算法)

    [toc] 在《算法导论》中举了买股票和割铁棒的例子来说明动态规划和贪心算法的主体思想。 贪心算法:总是做出在当前...

  • 动态规划---股票买卖

    动态规划 使用场景:重复子问题 步骤: 1、定义公式 2、初始化变量 3、写循环体 给定一个数组 prices...

  • LeetCode 188. 买卖股票的最佳时机 IV(Best

    188. 买卖股票的最佳时机 IV Python3 实现 动态规划 买卖股票的最佳时机 系列问题 通用型 解法 ...

网友评论

      本文标题:动态规划 买股票

      本文链接:https://www.haomeiwen.com/subject/ahegzttx.html