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

    Also the very first problem on EPI. 

    class Solution {
    public:
        int maxProfit(vector<int> &prices) {
            size_t len = prices.size();
            if (len <= 1) return 0;
            else if (len == 2)
            {
                if (prices[0] >= prices[1]) return 0;
                else return prices[1] - prices[0];
            }
            int len1 = len / 2;
            int len2 = len - len1;
    
            vector<int> v1; v1.assign(prices.begin(), prices.begin() + len1);
            int prof1 = maxProfit(v1);
            vector<int> v2; v2.assign(prices.begin() + len1, prices.end());
            int prof2 = maxProfit(v2);
            auto i1 = std::min_element(v1.begin(), v1.end());
            int min1 = *i1;
            auto i2 = std::max_element(v2.begin(), v2.end());
            int max1 = *i2;
            int prof3 = max1 - min1;
            return std::max(std::max(prof1, prof2), prof3);
        }
    };

     Update Aug. 18:

    Actually there's a O(n) algorthm. Since the logic should be: the current day's max profit is price@dayI - minPrice of day[0..i-1]. Then, a linear scan should work:

    class Solution {
    public:
        int maxProfit(vector<int> &prices) {
            size_t len = prices.size();
            if (len <= 1) return 0;
            
            int maxProfit = 0;
            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];
            }
            return maxProfit;
        }
    };
  • 相关阅读:
    python【第五篇】常用模块学习
    (三)训练HMM模块
    (二)杂项准备
    (四)看看成果
    (一)准备训练语音文件
    HTK语音识别示例(Ubuntu)
    RoboCup仿真3D TC笔记(2014年合肥中国公开赛 仿真3D比赛环境搭建)
    WebFont与页面font-icon图标研究
    Font Awesome使用方法
    css sprites拼合
  • 原文地址:https://www.cnblogs.com/tonix/p/3899268.html
Copyright © 2011-2022 走看看