Best Time to Buy and Sell Stock with Cooldown
2016-03-02 01:49
411 查看
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:
Solution 1:
Solution 2:
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 = 3 transactions = [buy, sell, cooldown, buy, sell]
Solution 1:
class Solution { public: int maxProfit(vector<int>& prices) { int n = prices.size(); if (n < 2) { return 0; } int buf ; buf[0] = 0; for (int i = 1; i < n; i++) { buf[i] = buf[i-1]; for (int j = 0; j < i; j++) { int temp = 0; if (prices[i] > prices[j]) { temp += prices[i]-prices[j]; } if (j-2 >= 0) { temp += buf[j-2]; } buf[i] = max(buf[i], temp); } } return buf[n-1]; } };
Solution 2:
int maxProfit(vector<int>& p) { if (p.size() < 2) return 0; int i, sz = p.size(); int ret = 0; vector<int> buy(sz, 0); vector<int> sell(sz, 0); buy[0] = -p[0]; for (i = 1; i < sz; ++i) { sell[i] = max(buy[i - 1] + p[i], sell[i - 1] - p[i - 1] + p[i]); if (ret < sell[i]) //record the max sell[i] ret = sell[i]; if (1 == i) buy[i] = buy[0] + p[0] - p[1]; else buy[i] = max(sell[i - 2] - p[i], buy[i - 1] + p[i - 1] - p[i]); } return ret; }
相关文章推荐
- 去除字符串首尾的空格
- ThingWorx : 1、创建Thing
- git系列一
- AndroidStudio刚安装完新建项目之后就报错无法运行
- android AIDL机制 电话拦截
- SQL Server中bcp命令的用法以及数据批量导入导出
- 判断一个数组是另一数组的子集
- Educational Codeforces Round 9
- 关于swift中约束会有的一些冲突解决
- cf#ecr9-D - Longest Subsequence
- 学习Linux决心书
- 程序员必须知道的10大基础实用算法及其讲解
- 个人进阶之路——安卓蓝牙模块(3)
- cf#ECR 9-C - The Smallest String Concatenation-水题
- JAVA二学(二)剖析String
- 143 php 接口
- PHP团队编码质量提升之道
- cf#ECR 9-B. Alice, Bob, Two Teams-DP
- c语言数据类型 之 内存对齐与位段
- 程序员必须知道的10大基础实用算法及其讲解