121. Best Time to Buy and Sell Stock
Leetcode
https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/
題目
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.解答
方法一
只需要紀錄兩個指標,就可以算出最大的獲利
過去最小的買進價格
min目前為止可以得到的最大獲利
profit
var maxProfit = function(prices) {
let min = Number.MAX_SAFE_INTEGER;
let profit = 0;
for(let i=0; i<prices.length; i++) {
const price = prices[i];
if (price < min) {
min = price;
}
if (price - min > profit) {
profit = price - min;
}
}
return profit;
};Runtime: 64 ms Beats 92.33% of users with JavaScript
Memory: 59.34 MB Beats 17.92% of users with JavaScript
方法二 - 雙指針
min 紀錄最低價
left 紀錄最低價時的 index
right 一直往右移動,當 right 遇到的價格低於 min 時,重設 min 與 left 的值
var maxProfit = function (prices) {
const length = prices.length;
if (length === 1) return 0;
let left = 0;
let right = 1;
let profit = 0;
let min = prices[left];
while(right !== length) {
const lastPrice = prices[left];
const todayPrice = prices[right];
if (todayPrice - lastPrice > profit) {
profit = todayPrice - lastPrice;
}
if (todayPrice < min) {
left = right;
min = prices[left];
}
right++;
}
return profit;
};Runtime: 56 ms Beats 99.03% of users with JavaScript
Memory: 58.56 MB Beats 44.47% of users with JavaScript
參考資料
Last updated
Was this helpful?
