题目描述
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.
原题解释:一个数组,第i个表示第i天股票的价格,如果只允许你买入和卖出一次股票,问你如何才能获得最大的利润?(即:最佳的买入和卖出时机)
解题思路:
此题需求出max(aj-ai)(其中0<=i<j<n);
1.暴力求解法:时间复杂度为O(n^2),两层遍历,选出最大值(方法自己想啦);
2.改进:一定要求出时间复杂度为O(n)的解法:
考虑:虽然最佳的买入时机未必是数组中最小值出现的地方,但是,在当前位置,一定要减去之前出现的最小值,才有可能出现最大利润,因此,我们开辟两个空间,一个用来记录当前记录之前的最小值previousMin,一个用来记录当前位置时的最大利润maxProfit.只有当prices[i]-previousMin>maxProfit时,我们才更新maxProfit=prices[i]-previousMin.并且,如果prices[i]<previousMin,我们还要更新previousMin=prices[i].代码如下:
public
class
Solution {
public
int
maxProfit(
int
[] prices) {
int
previousMin =
9999
;
int
maxProfit =
0
;
if
(prices.length<
2
){
return
0
;
}
for
(
int
i =
0
;i<prices.length;i++){
if
(prices[i]<previousMin){
previousM
in = prices[i];
}
if
(prices[i]-previousMin>maxProfit){
maxP
rofit = prices[i]-previousMin;
}
}
return maxP
rofit;
}
}
从该题中我们要明白在遍历数组中最需要保存的值以及如何去更新,更新的策略.
|