zoukankan      html  css  js  c++  java
  • 309.Best Time to Buy and Sell Stock with Cool down

    题目描述

    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)

    难度系数

    Medium

    Example

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

    解法:买入、卖出、休息一天各一个状态,

    class Solution {
        //参照连接https://www.cnblogs.com/jdneo/p/5228004.html
    public:
        int maxProfit(vector<int>& prices){
            if (prices.size() <= 1) return 0;
            vector<int> s0(prices.size(), 0);
            vector<int> s1(prices.size(), 0);
            vector<int> s2(prices.size(), 0);
            s1[0] = -prices[0];//表示买入后余剩的钱,最大值
            s0[0] = 0;//表示休息一天,最大值
            s2[0] = INT_MIN;//表示卖出,最大值
            for (int i = 1; i < prices.size(); i++) {
                s0[i] = max(s0[i - 1], s2[i - 1]);//休息前一天只能是休息或者是卖出。休息的最大值是前一天是休息和前一天卖出比较
                s1[i] = max(s1[i - 1], s0[i - 1] - prices[i]);//买入前一天可以是买入或者是休息,操作于一支股票,不可以连续买入。买入的最大值是前一天买入和前一天休息今天买入比较
                s2[i] = s1[i - 1] + prices[i];//卖出前一天只能是买入,卖出的最大值是前一天买入后加上当前价格
            }
            //返回卖出或者是休息一天的最大值
            return max(s0[prices.size() - 1], s2[prices.size() - 1]);
        }
    };
  • 相关阅读:
    国外保健品品牌介绍
    海淘第一单
    表查询语句与方法
    表与表关系
    表完整性约束
    表字段数据类型
    存储引擎
    数据库之MySQL基本操作
    MAC重置MySQL root 密码
    进程池、线程池、协程
  • 原文地址:https://www.cnblogs.com/AntonioSu/p/12806018.html
Copyright © 2011-2022 走看看