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]);
        }
    };
  • 相关阅读:
    git 更新代码
    jmeter 线程组之间传递动态变化的变量值
    MYSQL 使用存储过程批量更新表数据
    linux查看日志中特定字符串以及前后信息内容命令
    导出表结构 字段说明
    转 awk统计nginx每天访问最高的接口
    MySQL 同一字段匹配多个值
    Can't connect to local MySQL server through socket '/opt/lampp/var/mysql/mysql.sock' (2)
    转 Xshell ssh长时间连接不掉线设置
    Vs.net 常用命令行
  • 原文地址:https://www.cnblogs.com/AntonioSu/p/12806018.html
Copyright © 2011-2022 走看看