风口的猪-中国牛市--小米2016笔试题

题目来源:风口中的猪-中国牛市

题目描述

风口之下,猪都能飞。当今中国股市牛市,真可谓“错过等七年”。 给你一个回顾历史的机会,已知一支股票连续n天的价格走势,以长度为n的整数数组表示,数组中第i个元素(prices[i])代表该股票第i天的股价。 假设你一开始没有股票,但有至多两次买入1股而后卖出1股的机会,并且买入前一定要先保证手上没有股票。若两次交易机会都放弃,收益为0。 设计算法,计算你能获得的最大收益。 输入数值范围:2<=n<=100,0<=prices[i]<=100

示例1

 

输入
  3,8,5,1,7,8
输出
  12
题目思路:将数组分成两段,求两段最大子和

代码:

#include<bits/stdc++.h>
using namespace std;

class Solution {
public:
    int calculateMax(vector<int> prices) {
        vector<int> v;
        int max1,max2;
        for(int i=0;i<prices.size()-1;i++){
            v.push_back(prices[i+1]-prices[i]);
        }

        for(auto i:v) cout<<i<<' ';
        cout<<endl;

        int result=0;
        for(int i=0;i<v.size();i++){
            max1=max2=0;
            int temp=0;
            for(int j=0;j<=i;j++){
                temp+=v[j];
                temp=temp>0?temp:0;
                max1=max(max1,temp);
            }
            temp=0;
            for(int j=i+1;j<v.size();j++){
                temp+=v[j];
                temp=temp>0?temp:0;
                max2=max(max2,temp);
            }
            result=max(result,max1+max2);
        }
        return result;

    }
};

int main() {
    vector<int> v;
    v={5,15,56,26,62,65,57,69};
    Solution s;
    int result=s.calculateMax(v);
    cout<<result<<endl;
    return 0;
}
原文地址:https://www.cnblogs.com/ybf-yyj/p/9867842.html