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]);
        }
    };
  • 相关阅读:
    webpack常见的配置项
    详解javascript立即执行函数表达式(IIFE)
    javascript闭包—围观大神如何解释闭包
    hubilder打包+C#服务端个推服务实现
    vue学习笔记1-基本知识
    javascript中的字典
    javascript中获取元素尺寸
    php常见知识
    javascript中使用循环链表实现约瑟夫环问题
    ASP.NET Core 中的文件上传
  • 原文地址:https://www.cnblogs.com/AntonioSu/p/12806018.html
Copyright © 2011-2022 走看看