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;
}
};