Leetcode算法学习日志-309 Best Time to Buy and Sell Stock with Cooldown

来源:互联网 发布:无限极专属网络电视盒 编辑:程序博客网 时间:2024/05/22 14:55

Leetcode 309 Best Time to Buy and Sell Stock with Cooldown

题目原文

Say you have an array for which the ith element is the price of a given stock on dayi.

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]

题意分析

买卖股票,每次买必须在上一次卖完一天(或大于一天)以后,求最大收益是多少。

解法分析

这种买卖股票问题是典型的动态规划问题,对于某一天的最大收益,分两种情况,一种是这天hold了一支股票,另一种是手里没有股票。可以得到递归式如下:

hold[i]=max(hold[i-1],non[i-2]-price),non[i]=max(non[i-1],hold[i-1]+price)。对于第i天的收益和前一天的收益,可以用同一个变量表示,再前一天的可以用另一个新的变量表示,本题需要注意初始值得选取。C++代码如下:

class Solution {public:    int maxProfit(vector<int>& prices) {        int preNon=0,non=0,hold=INT_MIN,temphold;        for(auto price:prices){            temphold=hold;//temphold is not necessary            hold=max(hold,preNon-price);            preNon=non;            non=max(non,temphold+price);        }        return non;       }};
preNon用来存储non[i-2],由于hold的值要么取hold,要么为preNon-price,当为preNon-price时,non一定取前一次的non,所以不影响non的新值,因此temphold不必要。

阅读全文
0 0
原创粉丝点击