题目描述
假设把某股票的价格按照时间先后顺序存储在数组中,请问买卖交易该股票可能获得的最大利润是多少?
示例
输入: [7,1,5,3,6,4]
输出: 5
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。
输入: [7,6,4,3,1]
输出: 0
解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。
思路
1、问题转换,求 max(prices[j] - prices[i]) , 其中 i < j。
2、暴力解法,时间复杂度 O(N ^ 2)
public int maxProfit(int[] prices) {
if (prices == null || prices.length == 0) {
return 0;
}
int max = 0;
for (int i = 0; i < prices.length - 1; i++) {
for (int j = i + 1; j < prices.length; j++) {
int profit = prices[j] - prices[i];
if (max < profit) {
max = profit;
}
}
}
return max;
}
3、求最大利润,使用贪心算法。
- 明确最优解:最大利润max(prices[j] - prices[i]) , 其中 i < j
- 先求局部最优解:对于当前价格prices[j],找到在j之前的最小价格minPrice,得到局部最大利润profit = prices[j] - minPrice。
- 整合局部最优解,得到全局最优解:局部最大利润的最大值,即为最大利润。
public int maxProfit(int[] prices) {
if (prices == null || prices.length == 0) {
return 0;
}
int max = 0;
int minPrice = prices[0];
for (int i = 1; i < prices.length; i++) {
if (minPrice > prices[i]) {
minPrice = prices[i];
}
int profit = prices[i] - minPrice;
if (max < profit) {
max = profit;
}
}
return max;
}