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

    Refer: http://blog.unieagle.net/2012/12/05/leetcode%E9%A2%98%E7%9B%AE%EF%BC%9Abest-time-to-buy-and-sell-stock-iii%EF%BC%8C%E4%B8%80%E7%BB%B4%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92/

    If you had a O(n) to "Best Time to Buy and Sell Stock", it is not that far away from an AC to III. Initially, it reminds me http://poj.org/problem?id=2479, and I think they are quite similar.

    class Solution {
    public:
        int maxProfit(vector<int> &prices) {
            size_t len = prices.size();
            if (len <= 1) return 0;
    
            int maxProfit = 0;
    
            //    Pass 1: as Best Time to Buy and Sell Stock 
            vector<int> dp; dp.push_back(0);
            int lowest = prices[0];
            for (int i = 1; i < prices.size(); i++)
            {
                int currP = prices[i] - lowest;
                if (currP > maxProfit) maxProfit = currP;
                if (prices[i] < lowest) lowest = prices[i];
    
                dp.push_back(maxProfit);
            }
    
            //    Pass 2: 
            int ret = 0;
            maxProfit = 0;
            int highest = prices[len - 1];
            for (int i = len - 2; i >= 0; i--)
            {
                int currP = highest - prices[i];
                if (currP > maxProfit) maxProfit = currP;
                if (prices[i] > highest) highest = prices[i];
    
                //
                int currTotal = dp[i] + maxProfit;
                if (currTotal > ret) ret = currTotal;
            }
            return ret;
        }
    };
  • 相关阅读:
    数据结构
    ADC
    SPI
    定时器原理
    IO中断
    恩智浦样片申请
    UART
    随机生成数字验证码
    判断网络是否连接Internet
    清理SQL数据库日志
  • 原文地址:https://www.cnblogs.com/tonix/p/3921676.html
Copyright © 2011-2022 走看看