zoukankan      html  css  js  c++  java
  • Best Time to Buy and Sell Stock III

    题目:

    ay 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 at most two transactions.

    Note:
    You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

    解析:

    只能买卖两次,分别搞两个数组

    动态规划

    使用两个数组,forw和back。

    forw[i]表示从0到i的最优买卖值(低买高卖,为正)。需要一次从左往右遍历。

    back[i]表示从m-1到i的最差买卖值(高买低卖,为负)。需要一次从右往左遍历。

    再对应元素相减:forw[i]-back[i]的最大值即解。

    class Solution {
    public:
        int maxProfit(vector<int> &prices) {
            int m = prices.size();
            if(m == 0)
                return 0;
            
            int ret = 0;
            vector<int> forw(m, 0);
            vector<int> back(m, 0);
            
            //forward
            int curMin = prices[0];
            for(int i = 1; i < m; i  ++)
            {
                curMin = min(curMin, prices[i]);
                forw[i] = max(forw[i-1], prices[i]-curMin);
            }
            //backward
            int curMax = prices[m-1];
            for(int i = m-2; i >= 0; i --)
            {
                curMax = max(curMax, prices[i]);
                back[i] = min(back[i+1], prices[i]-curMax);
                
                ret = max(ret, forw[i]-back[i]);
            }
            
            return ret;
        }
    };
  • 相关阅读:
    PHP基础1
    U2-Net网络学习笔记(记录)
    C++贪吃蛇游戏
    实习期间学习基础学习整理
    week 2020.1.10-2020.1.15
    week 2021.1.04-2021.1.08
    week 2020.12.21-2020.12.31
    周记 week 2020-12.14-12.18
    几种读取图片和标签的方法
    图像风格转换(Style Transfer | 风格迁移综述)
  • 原文地址:https://www.cnblogs.com/raichen/p/4933017.html
Copyright © 2011-2022 走看看