算法: 买卖股票的时间 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
1. 当前值减去最小值法
class Solution {
public int maxProfit(int[] prices) {
int low = prices[0];
int max = 0;
int gap = 0;
for (int i = 1; i < prices.length; i++) {
low = prices[i] < low ? prices[i] : low;
gap = prices[i] - low;
max = Math.max(max, gap);
}
return max;
}
}
2. 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)