309. Best Time to Buy and Sell Stock with Cooldown *
来源:互联网 发布:淘宝欧缇丽旗舰店真假 编辑:程序博客网 时间:2024/06/06 09:24
class Solution {public: int maxProfit(vector<int>& prices) { int size = prices.size(); if (size == 0 || size == 1) return 0; if (size == 2) return prices[1] > prices[0] ? prices[1] - prices[0] : 0; int has[size] = {0}; int no[size] = {0}; has[0] = -prices[0]; no[0] = 0; has[1] = max(-prices[0], -prices[1]); no[1] = max(has[0] + prices[1], no[0]); for(int i = 2; i < size; i++){ has[i] = max(no[i - 2] - prices[i], has[i - 1]); no[i] = max(has[i - 1] + prices[i], no[i - 1]); } return no[size - 1]; }};
动态规划。两个状态数组,持股与不持股。
has[i]代表一个持股与不持股的序列,并且这个序列以持股为结尾(在第i天时是持股的)
no[i]代表一个持股与不持股的序列,并且此序列在第i天不持股
状态转移方程
has[i] = max(no[i - 2] - prices[i], has[i - 1]);no[i] = max(has[i - 1] + prices[i], no[i - 1]);讲道理这题对于没参加acm的我来说,想出这个解释挺费劲的。
然而这种题对于ACM大佬并不算秀,只是基本操作。
再努力刷题吧。
阅读全文
0 0
- 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
- 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
- 遇到一个非常坑的BUG!!关于Button的
- 关于jsp servlet和jfinal的基础知识
- js实现十种排序算法
- java分布式系统定时任务,如何保证多台服务只执行一次
- MySql中游标的定义与使用方式
- 309. Best Time to Buy and Sell Stock with Cooldown *
- [agc013e]Placing Squares
- dex分包之--------multidex包的配置使用
- 同服务器数据库之间的数据操作与不同服务器数据库之间的数据操作
- poj3253(贪心)
- ruby 的代码块
- 看唐僧如何玩转PMP
- IONIC 表单标签的使用
- 【Spring in action】基于Java配置SpringMVC中使用Spring及SpringMVC各种请求详解