您的位置:首页 > 其它

Lintcode 买卖股票的最佳时机

2017-07-28 11:11 357 查看
买卖股票的最佳时机

思路: 最大利润 为当前值- 前面最小值

1 lowest =prices[0],记为最小值,循环一次,记min(lowest,prices[i])为最小值;

2 profit= max(profit,prices[i] - lowest);profit 初值为0;

class Solution {
public:
/**
* @param prices: Given an integer array
* @return: Maximum profit
*/
int maxProfit(vector<int> &prices) {
// write your code here
int m = prices.size();
int profit = 0;
if (m < 2) {
return profit;
}
int lowest = prices[0];
for (int i = 0; i < m; i++) {
int current = prices[i];
profit = max(profit, current - lowest);
lowest = min(current, lowest);
}
return profit;
}
};


买卖股票的最佳时机||

class Solution {
public:
/**
* @param prices: Given an integer array
* @return: Maximum profit
*/
int maxProfit(vector<int> &prices) {
// write your code here
int m = prices.size();
int profit = 0;
if (m < 2) {
return 0;
}
for (int i = 0; i < m-1; i++) {
int j = prices[i+1] - prices[i];
if (j > 0) {
profit += j;
}
}
return profit;
}
};


买卖股票的最佳时机3

分析:动态规划法。以第i天为分界线,计算第i天之前进行一次交易的最大收益preProfit[i],和第i天之后进行一次交易的最大收益postProfit[i],最后遍历一遍,max{preProfit[i] + postProfit[i]} (0≤i≤n-1)就是最大收益。第i天之前和第i天之后进行一次的最大收益求法同Best Time to Buy and Sell Stock I

没有通过?????

vs上面是编译通过的,结果也正确。

#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;

class Solution {
public:
/**
* @param prices: Given an integer array
* @return: Maximum profit
*/
int maxProfit(vector<int> &prices) {
if (prices.size() < 2) return 0;

int n = prices.size();
vector<int> preProfit(n,0);
vector<int> postProfit(n,0);

int curMin = prices[0];
for (int i = 1; i < n; i++) {
curMin = min(curMin, prices[i]);
preProfit[i] = max(preProfit[i - 1], prices[i] - curMin);
}

int curMax = prices[n - 1];
for (int i = n - 2; i >= 0; i--) {
curMax = max(curMax, prices[i]);
postProfit[i] = max(postProfit[i + 1], curMax - prices[i]);
}
int maxProfit = 0;
for (int i = 0; i < n; i++) {
maxProfit =max(maxProfit, preProfit[i] + postProfit[i]);
}

return  maxProfit;
}
};
int main()
{
Solution test;//我们取一个名字为test的对象
cout << "请输入一串整数数组" << endl;
int num;
vector<int>b;
while (cin >> num)
{
b.push_back(num);
if (cin.get() == '\n')   //如果检测到用户回车,则结束输入
break;
}
test.maxProfit(b);
cout << test.maxProfit(b) << endl;
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: