zoukankan      html  css  js  c++  java
  • 股票收益最大问题

    题目:
    给定数组n, 包含n天股票的价格price,
    一个人一共最多可以买2手股票,但在第一手股票卖出去前不能买入第二手股票.
    如果不买,收益为0.
    假设每手只买1股,计算这个人最大收益.

    答案:

    #include <iostream>
    #include <vector>
    
    // 计算[first,last)之间的最大子序列和,并将每一步保存在result中
    template<class Iterator, class T>
    void MaxSubArray(Iterator first, Iterator last, std::vector<T> &result)
    {
        T max = 0;
        T sum = 0;
        for(;first!=last;first++){
            if(sum<0){
                sum = 0;
            }
            sum += *first;
            max = max>sum?max:sum;
            result.push_back(max);
        }
    }
    
    // 计算最大收益
    int MaxProfit(const std::vector<int> &prices)
    { 
        if(prices.size()<2){
            return 0;
        }
    
        // prices数组转换为涨跌幅数组
        std::vector<int> v;
        for(int i=1;i<prices.size();i++){
            v.push_back(prices[i]-prices[i-1]);
        }
        
        // 从左到右计算每个最大子序列和
        std::vector<int> left;
        left.push_back(0);
        MaxSubArray(v.begin(),v.end(),left);
     
        // 从右到左计算每个最大子序列和
        std::vector<int> right;
        right.push_back(0);
        MaxSubArray(v.rbegin(),v.rend(),right);
        
        // 将数组分为左右两部分,左右相加求最大值
        int max = 0;
        auto iterLeft = left.begin();
        auto iterRight = right.rbegin();
        for(;iterLeft != left.end(); iterLeft++, iterRight++){
            int tmp = *iterLeft + *iterRight;
            max = max>tmp?max:tmp;
        }
     
        return max;
    }
    
    
    int main()
    {
        std::vector<int> prices = {3,8,5,1,7,8};
        int result = MaxProfit(prices);
        std::cout<<result<<std::endl;
    
        return 0;
    }
    
  • 相关阅读:
    在关闭窗体时弹出对话框
    使应用程序在进程中消失
    禁用窗口上的关闭按钮
    洛谷P1080 国王游戏
    洛谷P1443 马的遍历
    算法竞赛入门经典第二版 随笔1
    AcWing 794. 高精度除法
    AcWing 793. 高精度乘法
    AcWing 792. 高精度减法
    AcWing 791. 高精度加法
  • 原文地址:https://www.cnblogs.com/walkinginthesun/p/10147191.html
Copyright © 2011-2022 走看看