给你一个整数数组 prices ,其中 prices[i] 表示某支股票第 i 天的价格。
在每一天,你可以决定是否购买和/或出售股票。你在任何时候 最多 只能持有 一股 股票。你也可以先购买,然后在 同一天 出售。
返回 你能获得的 最大 利润 。
示例 1:
输入:prices = [7,1,5,3,6,4]
输出:7
解释:在第 2 天(股票价格 = 1)的时候买入,在第 3 天(股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5 - 1 = 4 。
随后,在第 4 天(股票价格 = 3)的时候买入,在第 5 天(股票价格 = 6)的时候卖出, 这笔交易所能获得利润 = 6 - 3 = 3 。
总利润为 4 + 3 = 7 。
如果股票一直上涨,只需要找到股票上涨的最大值和股票开始上涨的最小值,计算他们的差就是这段时间内股票的最大利润。如果股票下跌就不用计算,最终只需要把所有股票上涨的时间段内的利润累加就是我们所要求的结果
作者:数据结构和算法
链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/x2zsx1/?discussion=KwAnTs
来源:力扣(LeetCode)
public int maxProfit(int[] prices) {
if (prices == null || prices.length < 2) //这里看是不是够长
return 0;
int total = 0, index = 0, length = prices.length;
while (index < length) {
while (index < length - 1 && prices[index] >= prices[index + 1])
index++;//如果股票下跌就一直找,直到找到股票开始上涨为止
int min = prices[index];//定为股票开始上升的值
while (index < length - 1 && prices[index] <= prices[index + 1])
index++;//一直找到股票上涨的最大值为止
total += prices[index++] - min;//先赋值在++,计算这段上涨时间的差值,然后进入最外层循环继续寻找后面的上涨差值
}
return total;
}
作者:数据结构和算法
链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/x2zsx1/?discussion=KwAnTs
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。