• 股票收益最大问题


    题目:
    给定数组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;
    }
    
  • 相关阅读:
    Oracle 18c新特性一览
    iOS xcode缓存问题
    预编译头文件
    iOS 限制UITextField输入字符
    网络通信之 字节序转换原理与网络字节序、大端和小端模式
    iOS 库文件制作
    iOS 全屏布局
    内存问题 动态加载地址和运行时地址
    申请工作居住证政策解答
    phpsession配置
  • 原文地址:https://www.cnblogs.com/walkinginthesun/p/10147191.html
Copyright © 2020-2023  润新知