风口之下,猪都能飞。当今中国股市牛市,真可谓“错过等七年”。 给你一个回顾历史的机会,已知一支股票连续n天的价格走势,以长度为n的整数数组表示,数组中第i个元素(prices[i])代表该股票第i天的…

  • Post author:
  • Post category:其他


// ConsoleApplication10.cpp : 定义控制台应用程序的入口点。

//

#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;

class Solution {
public:
    /**
    * 计算你能获得的最大收益
    *
    * @param prices Prices[i]即第i天的股价
    * @return 整型
    */
    int calculateMax(vector<int> prices) {
    
        vector<int> vec1, vec2;
        int earn = 0, max = earn;;
        for (int i = 0;i < prices.size() ;i++)
        {
            vec1.push_back(prices[i]);
            vec2.clear();
            for (int j = i+1;j < prices.size();j++)
            {
                vec2.push_back(prices[j]);
            }
            earn = calculateEarn(vec1) + calculateEarn(vec2);
            if (earn > max)
            {
                max = earn;
            }
        }
        return max;
    }
    int calculateEarn(vector<int> prices) {
        //没有一笔交易
        int  earn = 0;
        //交易一次
        int max = earn;
        for (int i = 0;i < prices.size();++i)
        {
            //第i天买入
            int out = prices[i];

            for (int j = i;j < prices.size();++j)
            {
                //第j填卖出
                int in = prices[j];
                earn = in - out;
                if (earn > max)
                {
                    max = earn;
                }
            }
        }
        return max;
    }
};

int main()
{
    Solution so;
    //vector<int> prices = { 3,8,5,1,7,8 };
    
    vector<int> prices = { 10, 7, 3, 1 };
    cout << "收益:" << so.calculateMax(prices)<<endl;
    cout << "收益:" << so.calculateEarn(prices) << endl;;
    cout << endl;
    return 0;
}

//先计算交易一次的

//然后计算交易两次的

转载于:https://www.cnblogs.com/wdan2016/p/6413659.html