题目描述
给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。
你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。
返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 。
示例 1:
输入:[7,1,5,3,6,4]
输出:5
解释:在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格;同时,你不能在买入前卖出股票。
示例 2:
输入:prices = [7,6,4,3,1]
输出:0
解释:在这种情况下, 没有交易完成, 所以最大利润为 0。
提示:
- 1 <= prices.length <= 105
- 0 <= prices[i] <= 104
暴力解法
class Solution {
public int maxProfit(int[] prices) {
int ans = 0;
for (int i = 0; i < prices.length; i++) {
for (int j = i + 1; j < prices.length; j++) {
ans = Math.max(prices[j] - prices[i], ans);
}
}
return ans;
}
}
暴力解法会超时。
最大值和最小值求差
正向遍历,每个位置上的最小值和最大值求差,取差值的最大值
class Solution {
public int maxProfit(int[] prices) {
int[] mins = new int[prices.length];
for (int i = 0; i < prices.length; i++) {
if (i == 0) {
mins[i] = prices[i];
} else {
mins[i] = Math.min(prices[i], mins[i-1]);
}
}
int[] maxs = new int[prices.length];
for (int i = 0; i < prices.length; i++) {
if (i == 0) {
maxs[i] = prices[i];
} else {
//这里是可以优化的,因为如果maxs[i-1] > prices[i], 则取prices[i]
//否则, Math.max(maxs[i-1], prices[i]) 取maxs[i-1]和prices[i]的较大值
//那么可以保证,maxs[i] 始终等于 price[i],所以 maxs 数组可以去掉
maxs[i] = maxs[i-1] > prices[i] ? prices[i] : Math.max(maxs[i-1], prices[i]);
}
}
int ans = 0;
for (int i = 0; i < prices.length; i++) {
ans = Math.max(maxs[i] - mins[i], ans);
}
return ans;
}
}
最小值和当前位置求差
从最大值和最小值求差优化而来,去掉 maxs 数组,同时将 mins 数组也去掉,只使用一个变量 min 记录最小值
class Solution {
public int maxProfit(int[] prices) {
int ans = 0;
int min = Integer.MAX_VALUE;
for (int i = 0; i < prices.length; i++) {
min = Math.min(min, prices[i]);
ans = Math.max(prices[i] - min, ans);
}
return ans;
}
}
最小值和当前位置求差再优化
class Solution {
public int maxProfit(int[] prices) {
int ans = 0;
int min = Integer.MAX_VALUE;
for (int i = 0; i < prices.length; i++) {
//这里加一步判断是为了少执行一次Math.max(ans, prices[i]-min);
//当min > prices[i],min = prices[i], 此时 prices[i]-min = 0,不用再去和 ans 进行比较了
if (min > prices[i]) {
min = prices[i];
} else {
ans = Math.max(ans, prices[i]-min);
}
}
return ans;
}
}
文章标签
冬眠
博主专注于技术、阅读与思考。在这里记录学习、思考与生活。
