携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第21天,点击查看活动详情
Leetcode:leetcode.cn/problems/gu…
GitHub : github.com/nateshao/le…
剑指 Offer 63. 股票的最大利润
假设把某股票的价格按照时间先后顺序存储在数组中,请问买卖该股票一次可能获得的最大利润是多少?
示例 1:
输入: [7,1,5,3,6,4]
输出: 5
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。
示例 2:
输入: [7,6,4,3,1]
输出: 0
解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。
思路1:暴力破解
面试尽量不要这样写。
- 双层循环遍历
if (max < prices[j] - prices[i]) max = prices[j] - prices[i];
/**
* 暴力破解
* 直接双重循环比较
*
* @param prices
* @return
*/
public int maxProfit(int[] prices) {
int max = 0;
for (int i = 0; i < prices.length; i++) {
for (int j = i + 1; j < prices.length; j++) {
if (max < prices[j] - prices[i]) max = prices[j] - prices[i];
}
}
return max;
}
Go
func maxProfit(prices []int) int {
max := 0
for i := 0; i < len(prices); i++ {
for j := i + 1; j < len(prices); j++ {
if max < prices[j]-prices[i] {
max = prices[j] - prices[i]
}
}
}
return max
}
思路2:动态规划
思路:
- 记录购买最少的价格
- 记录当前最高的利润(当前价格减去1.记录购买最少的价格)
- 遍历一次数组,维护这两个变量即可。
Go
func maxProfit(prices []int) int {
profix := 0
buyPrice := math.MaxInt32
for _, price := range prices {
if buyPrice > price {
buyPrice = price
}
if price-buyPrice > profix {
profix = price - buyPrice
}
}
return profix
}
java
/**
* 动态规划
* 1. 遍历一遍
* 2. 判断比较最小值,如果前一位比后一位小,就更新最小值
* 3. 更新利润,比较前一位与后一位比较,更新利润,取最大值
*
* @param prices
* @return
*/
public int maxProfit2(int[] prices) {
int max = 0;
for (int i = 1; i < prices.length; i++) {
max = Math.max(max, prices[i] - prices[i - 1]);
if (prices[i] > prices[i - 1]) prices[i] = prices[i - 1];
}
return max;
}
public int maxProfit(int[] prices) {
int profix = 0; // 利润
int cost = Integer.MAX_VALUE; // 花费
for (int price : prices) {
cost = Math.min(cost, price);
profix = Math.max(profix, price - cost);
}
return profix;
}