leetcode problem 309. Best Time to Buy and Sell Stock with Cooldown

本文介绍了一个股票买卖算法的设计,该算法遵循特定的交易规则并利用动态规划实现最优利润计算。通过一个示例输入展示了如何通过一系列交易操作达到最大收益。

Description

Say you have an array for which the iii-th 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:

Input: [1,2,3,0,2]
Output: 3 
Explanation: transactions = [buy, sell, cooldown, buy, sell]

Solution

  1. 一开始的想法是贪心(虽然直觉告诉我会爆掉)但是想先写一个,结果211个test cases, 过了209个 time limit exceeded.
  2. 然后打算用动归做,但我已经太久不写动归的题目了,状态啊,转移条件都忘了。 直接开了个数组存以前的结果,算法复杂度是O(N^2). 过是过了,但是:
    Runtime: faster than 9.12% of C++ online submissions
  3. 看了discussion区,dietpepsi 大神提供了一种很简明的思路:

代码如下:

class Solution {
public:    
    int maxProfit(vector<int>& prices) {
        int buy(INT_MIN),sell(0),preSell(0),preBuy;
        for(int price:prices)
        {
            preBuy = buy;
            buy = max(preSell-price,buy);
            preSell = sell;
            sell = max(preBuy + price, sell);
        }
        return sell;
    }
};

结果:

Runtime: faster than 100.00% of C++ online submissions
Memory Usage: less than 100.00% of C++ online submissions

c++11太好用了啊

20190401
tbc

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值