题目:
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.
代码:
class Solution {
public:
int maxProfit(vector<int>& prices) {
if (prices.empty() || prices.size() == 1)
{
return 0;
}
else{
int max = -pow(2,16);
unsigned int pos = prices.size()-1;
for (unsigned int i = 1; i<prices.size(); i++)
{
if ((prices[i] - prices[0]) > max)
{
max = prices[i] - prices[0];
pos = i;
}
}
for (unsigned int i = 1; i<prices.size()-1; i++)
{
if (pos >= i) //若卖出的最高价格的坐标大于此时买进的坐标,只需相减即可得此时买进的最大利润
{
if (max <0 && pos == i) //表明后面所有的价格都比i-1的价格要低
{
pos = pos + 1;
max = prices[pos] - prices[i];
}
else{ //表明从i到末尾的价格至少有一个比i-1的要高
if (max < (prices[pos] - prices[i])) //此时卖出所获利润最高
{
max = (prices[pos] - prices[i]);
}
}
continue; //当前买进就不需再进行后续的遍历找最大利润了
}
for (unsigned int j = prices.size() - 1; j>i; j--)
{
if (prices[j] > prices[i]) //卖出价格比买进价格高
{
if (max < (prices[j] - prices[i]))
{
max = prices[j] - prices[i];
pos = j;
}
}
}//for_j
}//for_i
return max >0 ? max : 0;
}
}
};
结果:
Submission Result: Time Limit Exceeded
思路:
先以第一个元素为买进价格,然后考虑接下来最为合理的卖出价格,即prices[pos]
然后遍历后续的价格,作为可能的买进价格。当pos >=i时,即表明最高卖出的价格时间在买进时间i的后面。
max < (prices[pos] - prices[i]))
表明此时买进收益会更好,此时只需修改收益max即可。max <0 && pos == i
当max< 0时,说明之后卖出的价格都比买进的低。且pos == i表明此时即为卖出的最高价,为了后续减少遍历次数,即实现判断pos >= i故pos =pos+1;o(╯□╰)o,结果超时。。。决定过段时间回过头再看问题,看能不能有一种重新的思路。