标签:
问题描述:
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
解决方案:
动态规划解法:
profit[i]数组表示在第i天卖出获得的最大利润。
class Solution {
public:
int maxProfit(vector<int> &prices) {
if(prices.empty())
{
return 0;
}
int* profit = new int[prices.size()];
profit[0] = 0;
int maxx = profit[0];
for(int i = 1;i<prices.size();i++)
{
if(prices[i]>=prices[i-1])
{
profit[i] = profit[i-1]+ prices[i] - prices[i-1];
}else{
if(prices[i-1]-profit[i-1]<prices[i])
profit[i] = prices[i] - prices[i-1]+profit[i-1];
else{
profit[i] =0;
}
}
if(profit[i]>min)
maxx = profit[i];
}
return maxx;
}
};
版权声明:本文为博主原创文章,未经博主允许不得转载。
Best Time to Buy and Sell Stock
标签:
原文地址:http://blog.csdn.net/leosha/article/details/46687431