题目:
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.
思想:1. 因为只可以交易一次,所以可以看成求数组的最大差(注意:先买后卖,所以只可能是后面的数减去前面的数);
2. 为了程序不超时,先求出极值(局部最大和最小值),放在vector中
代码:
class Solution {
public:
int maxProfit(vector<int> &prices) {
vector<int> result;
int j = 0;
int max_dis = 0;
int n = prices.size();
while(j < n) {
while(j+1 < n && prices[j] >= prices[j+1])
j++;
if(j < n-1) {
result.push_back(prices[j]);
j++;
while(j+1 < n && prices[j] <= prices[j+1])
j++;
result.push_back(prices[j]);
}
j++;
}
int sz = result.size();
for(int i = 0; i < sz-1; i += 2) {
for(int j = i+1; j < sz; j += 2) {
int tmp = result[j] - result[i];
if(tmp > max_dis)
max_dis = tmp;
}
}
return max_dis;
}
};
上面第一次实现的比较复杂。
参考http://blog.youkuaiyun.com/pickless/article/details/12033745
使用cur_min表示之前股票的最低价,max_profit表示当前的股票最大利益
class Solution {
public:
int maxProfit(vector<int> &prices) {
if(prices.size() == 0)
return 0;
int max_profit = 0, cur_min = prices[0];
for(int i = 1; i < prices.size(); i++) {
int tmp = prices[i] - cur_min;
if(tmp > max_profit)
max_profit = tmp;
if(prices[i] < cur_min)
cur_min = prices[i];
}
return max_profit;
}
};