动态规划-309. Best Time to Buy and Sell Stock with Cooldown
来源:互联网 发布:qq业务乐园源码 编辑:程序博客网 时间:2024/06/07 03:29
题目:
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) with the following restrictions:
- You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
- After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
Example:
prices = [1, 2, 3, 0, 2]maxProfit = 3transactions = [buy, sell, cooldown, buy, sell]
题意解读:给定一个数组,数组的第i各元素就是第i天的股票的价格。你可以有任意多的交易次数。但是有两点限制,①你必须在卖出之后才能重新购买
②再卖出股票之后,你不能在第二天购买股票。至少要休息一天
class Solution { public int maxProfit(int[] prices) { if(prices.length == 0) return 0; //定义三种状态数组 s0,s1,s2 int[] s0 = new int[prices.length];//状态s2和状态s0休息之后进入s0 int[] s1 = new int[prices.length];//状态s0购买股票或者状态s1休息进入s1 int[] s2 = new int[prices.length];//状态s1卖出股票进入s2 //初始化三种状态 s0[0] = 0;//一开始,如果你并没有任何股票,休息之后,还是0 s1[0] = -prices[0];//买进prices[0]。所以是-price[0] s2[0] = 0;//一开始并没有拥有股票,所以不存在卖出。所以是0 for(int i = 1; i < prices.length; i++){ s0[i] = Math.max(s0[i-1],s2[i-1]); s1[i] = Math.max(s0[i-1] - prices[i],s1[i-1]); s2[i] = s1[i-1] + prices[i]; } return Math.max(s0[prices.length-1],s2[prices.length-1]); }}
阅读全文
0 0
- 309.leetcode Best Time to Buy and Sell Stock with Cooldown(medium)[动态规划]
- 309. Best Time to Buy and Sell Stock with Cooldown 类别:动态规划 难度:medium
- leetcode 309. Best Time to Buy and Sell Stock with Cooldown 动态规划DP
- 动态规划-309. Best Time to Buy and Sell Stock with Cooldown
- 309.Best Time to Buy and Sell Stock with Cooldown
- 309. Best Time to Buy and Sell Stock with Cooldown
- 309. Best Time to Buy and Sell Stock with Cooldown
- 309. Best Time to Buy and Sell Stock with Cooldown
- 309. Best Time to Buy and Sell Stock with Cooldown
- 309. Best Time to Buy and Sell Stock with Cooldown
- 309. Best Time to Buy and Sell Stock with Cooldown
- 309. Best Time to Buy and Sell Stock with Cooldown
- 309. Best Time to Buy and Sell Stock with Cooldown
- 309. Best Time to Buy and Sell Stock with Cooldown
- 309. Best Time to Buy and Sell Stock with Cooldown
- 309. Best Time to Buy and Sell Stock with Cooldown
- 309. Best Time to Buy and Sell Stock with Cooldown
- 309. Best Time to Buy and Sell Stock with Cooldown
- 二分和三分总结与误区分析
- LAMP/LNMP安装与配置
- c语言初步学习记录
- Java 多线程 (PART X)synchronized (III)synchronized的几种格式
- Turtle
- 动态规划-309. Best Time to Buy and Sell Stock with Cooldown
- TaotaoResult
- C语言操作符简介
- html规范和兼容测试
- Android点击空白区域,隐藏输入法软键盘
- JS的跨域问题
- leetcode 39. Combination Sum
- Java版本 排序算法总结
- MFC一些语法笔记