121. 买卖股票的最佳时机 - 力扣(LeetCode) (leetcode-cn.com)
难度:简单
题目描述:给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。
你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。
返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 。
类型一样的题
股票问题系列通解(转载翻译) - 力扣(LeetCode) (leetcode-cn.com)
分析
本题为求股票买入卖出之间的最大利润,实际上是求数组中最大数和最小数的差值问题,
但是股票的买卖存在这先买后卖的顺序性,故寻找数组中最大数和最小数则为相对于位置来说的
例如数组[7,1,5,3,6,4]中,最小值为1,最大值为7,但是不存在先卖后买的情况,所以只能寻找最小值1后面的最大值6,故差值为5,即利润为5
清楚了题目要求后就变得简单了很多,可以使用双指针的方法,一个指针为buy,指向买股票时的价格,另一个指针为sale,指向卖股票时的价格
profit = sale - buy
这时就可以遍历数组,通过遍历寻找买股票的最低点和卖股票的最高点。
由于1 <= prices.length <= 105 所以对于buy和sale取值之前需要判断数组长度,如果数组长度为1,则直接返回0。
并且此方法还有一种情况,即数组就两个元素,例如:[7,1]
这种情况下profit初始化为-6,不符合题目标准,所以在返回值处需要进行判断
优化:
本题实质上不需要考虑sale值的存储,因为sale值可以通过遍历数组得到prices[i],
而且profit值的变更也可以不考虑sale值
解题
优化前
class Solution {
public int maxProfit(int[] prices) {
if (prices.length < 2){
return 0;
}
int buy = prices[0];
int sale = prices[1];
int profit = sale - buy;
for (int i = 1; i < prices.length - 1; i++) {
if (prices[i] < buy) {
buy = prices[i];
}
if (prices[i + 1] - buy > profit) {
sale = prices[i + 1];
profit = sale - buy;
}
}
return profit > 0 ? profit : 0;
}
}
优化后
class Solution {
public int maxProfit(int[] prices) {
int buy = prices[0];
int profit = 0;
for (int i = 1; i < prices.length; i++) {
if (prices[i] - buy > profit) {
profit = prices[i] - buy;
}
buy = prices[i] < buy ? prices[i] : buy;
}
return profit;
}
}