say you have an array for witch the i th 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.)
Example 1
一下就能想到的是维持两个指针,伪代码如下:
for(int i = 0; i <= array[last_index]; ++i){
for(int j = 0; i < i; i++)
statement...
}
}
时间复杂度是O(n^2)
下面是时间复杂度为O(n)的approach:
class Solution {
public:
int maxProfit(vector<int>& prices) {
int minprice = INT_MAX;
int max_difference = 0;
for(vector<int>::iterator iter = prices.begin(); iter != prices.end(); ++iter){
if(*iter < minprice)
minprice = *iter;
if(*iter-minprice > max_difference)
max_difference = *iter-minprice;
}
return max_difference;
}
};
本文介绍了一种寻找股票买卖最佳时机以获得最大利润的算法。该算法能够在一次交易限制下,通过一次遍历找到最优解,时间复杂度为O(n)。
3980

被折叠的 条评论
为什么被折叠?



