121.Best Time to Buy and Sell Stock
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.
Example 1:
Input: [7, 1, 5, 3, 6, 4]
Output: 5
max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
Example 2:
Input: [7, 6, 4, 3, 1]
Output: 0
In this case, no transaction is done, i.e. max profit = 0.
方法一:暴力求解
public int maxProfit(int[] prices) {
int maxprofit = 0;
for(int i = 0; i < prices.length - 1; i++){
for(int j = i + 1; j < prices.length; j++){
maxprofit = Math.max(maxprofit, prices[j] - prices[i]);
}
}
return maxprofit;
}
超时,未通过。
复杂度分析:
时间复杂度:O(n^2)
空间复杂度:O(1)
方法二:Accepted
要找到最大利润,我们关心的是价格最小值,以及价格最小值之后的利润。所以,我们用两个变量:一个记录当前价格的最小值,另一个记录当前利润的最大值。
public int maxProfit2(int[] prices) {
int maxprofit = 0;
int minprice = Integer.MAX_VALUE;
for(int i = 0; i < prices.length; i++){
if(prices[i] < minprice)
minprice = prices[i];
else if(prices[i] - minprice > maxprofit)
maxprofit = prices[i] - minprice;
}
return maxprofit;
}
复杂度分析:
时间复杂度:O(n)
空间复杂度:O(1)