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.
这道题目如果不跟大家解释一下的话,很多人会摸不着头脑?普通的做法是o(n**2)的,比较有想法的可以变成o(2*n),最好的是o(n)class Solution {
public:
int maxProfit(vector<int> &prices) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int maxVal=0;
int prev=0;
int count=prices.size();
for(int i=count-1 ; i>=0 ; i--){
if(prices[i]>maxVal)
maxVal=prices[i];
if(maxVal-prices[i]>prev)
prev=maxVal-prices[i];
}
return prev;
}
};
比较脑残的做法是:对于每一个数,求出这个数后面最大的数,然后用这个最大的数减去当前的这个数,再看看有没有比上一个数用相同的做法得出的要大。
高级一点的做法是进行预处理,既然每次都要循环求每个数后面数中最大的,那么我可以倒过来循环一次,先求出每个数后面数中最大的存起来,再从头开始循环一遍
最高级的做法当然是上面给出的代码,上面的代码是逆向遍历,当然也可以正向遍历,逆向遍历要做的就是记住到当前这个数为止的最大值,然后用当然这个最大值减去当前这个数。正向遍历就要记住到当前在这个数位置的最小值,然后每次用当前这个数减去这个最小值,最后取最大的。