题目
给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。
你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。
返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/best-time-to-buy-and-sell-stock
方法1:暴力循环(超时)
作者:本人
思路:
从第一个数开始,为它寻找后面的数能与之作差的结果,找到最大的结果返回。
class Solution {
public int maxProfit(int[] prices) {
int len = prices.length;
int res = 0;
for (int i = 0; i < len-1; i++) {
int max = prices[i+1];
for (int j = i+1; j < len; j++) {
if (prices[j] > max){
max = prices[j];
}
}
res = max(res , max - prices[i]);
}
return res;
}
}
方法2:一次遍历
作者:力扣官方
我们来假设自己来购买股票。随着时间的推移,每天我们都可以选择出售股票与否。那么,假设在第 i 天,如果我们要在今天卖股票,那么我们能赚多少钱呢?
显然,如果我们真的在买卖股票,我们肯定会想:如果我是在目前来说历史最低点买的股票就好了!太好了,在题目中,我们只要用一个变量记录一个历史最低价格 minprice,我们就可以假设自己的股票是在那天买的。那么我们在第 i 天卖出股票能得到的利润就是 prices[i] - minprice。
因此,我们只需要遍历价格数组一遍,记录历史最低点,然后在每一天考虑这么一个问题:如果我是在历史最低点买进的,那么我今天卖出能赚多少钱?当考虑完所有天数之时,我们就得到了最好的答案。
注意目前来说历史最低,不是数组中的最低
有区别的:例如数组[ 2 , 99 , 1 , 10 ],数组中最低是“1”,那难道结果就是 在“1”买入,在“10”售出吗,那样只赚了10-1=9。
当我们从左往右遍历数组的时候,当遍历到“99”时,此时“2”才是当前历史最低点,我们计算在“2”买入,在“99”售出,转的是99-2=97,将97暂时存下来,遍历到“10”时,当前历史最低是 “1”,我们算的赚10-1=9,再拿9与前面的97比较,我们选择利润大的。
class Solution {
public int maxProfit(int[] prices) {
int len = prices.length;
int minIndex = 0;
int res = 0;
for (int i = 1; i < len; i++) {
if (prices[i] < prices[minIndex]){
minIndex = i;
}else res = Math.max(res , prices[i] - prices[minIndex]);
}
return res;
}
}
这道题虽然是简答题,但如果想不到一次遍历的话,那还是很难的,有这个思路了,那就非常简单。