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;
    }
    
  • 相关阅读:
    Zookeeper 集群安装
    Jexus部署.Net Core项目
    NetCore1.1+Linux部署初体验
    Linux初学
    高可用Redis服务架构分析与搭建
    前端开发JS白板编程题目若干
    Javascript中的Microtask和Macrotask——从一道很少有人能答对的题目说起
    ES6原生Promise的所有方法介绍(附一道应用场景题目)
    HTML的iframe标签妙用
    漫谈PHP代码规范
  • 原文地址:https://www.cnblogs.com/walkinginthesun/p/10147191.html
Copyright © 2011-2022 走看看