您的位置:首页 > 其它

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

2017-02-18 17:25 1216 查看
// 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;
}

//先计算交易一次的

//然后计算交易两次的
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐