您的位置:首页 > 其它

LeetCode | Best Time to Buy and Sell Stock(股票购买和抛售问题)

2014-08-15 11:18 471 查看
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.
题目解析:
给一堆数据,找到两个数之差的最大值,大数要在小数之后。

方案一:

很直观的方法:每一个元素为起点,让后面的数于该数相减,保存最大值;这样循环n次即可。时间复杂度为O(n^2)。大数据超时。

class Solution {
public:
int maxProfit(vector<int> &prices) {
int n = prices.size();
if(n == 0 || n == 1)
return 0;
int res = 0;
for(int i = 0;i < n-1;i++){
for(int j = i+1;j < n;j++){
if(prices[j] - prices[i] > res)
res = prices[j] - prices[i];
}
}
return res;
}
};


方案二:

如果我们不仅位置最大值也维持一个最小的数呢?当我们从前向后遍历的时候,用min记录下i之前的最小的数据,那么以i为大数的差值为a[i]-min,然后判断是否要更新res。这样时间复杂度就降低了很多。

有两个思考点:

1、我们一般找数据是像后找,也难怪,这个题目大数必须要在小数的后面,这样就限制了我们的思维。但如果变换一下的话,以大数为结尾,找前面的小数,能行的通。

2、既然找的话,也免不了一个一个去比较。我们要找最小数,就像维持最大值res一样,维持一个最小数变量min。

总的来说,要有逆向思维,碰到这种找最值的问题,可以用变量来简化查找。

class Solution {
public:
int maxProfit(vector<int> &prices) {
int n = prices.size();
if(n == 0 || n == 1)
return 0;
int res = 0;
int min = prices[0];
for(int i = 1;i < n;i++){
if(prices[i] < min)
min = prices[i];
else{
if(prices[i]-min > res)
res = prices[i]-min;
}
}
return res;
}
};


方案三:

如果再变换一下思路,我们从后向前便利呢?也同样维持一个max,当求以i为小数的时候,就用i+1...n中的最大值max-a[i]即可。

如果一个问题,不好思考的时候,尽量反向去考虑。

class Solution {
public:
int maxProfit(vector<int> &prices) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (prices.size() == 0)
return 0;

int maxPrice = prices[prices.size()-1];
int ans = 0;
for(int i = prices.size() - 1; i >= 0; i--)
{
maxPrice = max(maxPrice, prices[i]);
ans = max(ans, maxPrice - prices[i]);
}

return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐