算法: 买卖股票的时间 121. Best Time to Buy and Sell Stock
Posted 架构师易筋
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了算法: 买卖股票的时间 121. Best Time to Buy and Sell Stock相关的知识,希望对你有一定的参考价值。
121. Best Time to Buy and Sell Stock
You are given an array prices where prices[i] is the price of a given stock on the ith day.
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
Example 1:
Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
Example 2:
Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.
Constraints:
- 1 <= prices.length <= 105
- 0 <= prices[i] <= 104
Kadane 的算法
解决这个问题的逻辑与使用Kadane’s Algorithm. 由于到目前为止还没有任何机构提到这一点,我认为每个人都知道这是一件好事。
所有直接的解决方案都应该有效,但是如果面试官通过给出价格差异数组来稍微扭曲问题,例如:for 1, 7, 4, 11,如果他给出0, 6, -3, 7,你最终可能会感到困惑。
这里的逻辑是计算maxCur += prices[i] - prices[i-1]原始数组的差值 ( ),并找到一个利润最大的连续子数组。如果差值低于 0,则将其重置为零。
-
maxCur = current maximum value
-
maxSoFar = maximum value found so far
class Solution
public int maxProfit(int[] prices)
int maxCur = 0, maxSofar = 0;
for (int i = 1; i < prices.length; i++)
maxCur += prices[i] - prices[i - 1];
maxCur = Math.max(0, maxCur);
maxSofar = Math.max(maxSofar, maxCur);
return maxSofar;
参考
https://leetcode.com/problems/best-time-to-buy-and-sell-stock/discuss/39038/Kadane’s-Algorithm-Since-no-one-has-mentioned-about-this-so-far-%3A)-(In-case-if-interviewer-twists-the-input)
以上是关于算法: 买卖股票的时间 121. Best Time to Buy and Sell Stock的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode] 121. Best Time to Buy and Sell Stock 买卖股票的最佳时间
121.买卖股票 Best Time to Buy and Sell Stock