# 121. Best Time to Buy and Sell Stock.js

找一個陣列裡的最大最小值,可以先設 min = Number.MAX_SAFE_INTEGER,max = Number.MIN_SAFE_INTEGER

LeetCode

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction
 (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

input: 一組陣列代表某一個股票在七天內的價錢
output: 算出哪天賣最劃算 (一定要先買再賣)
Example 1:

Input: [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.
             Not 7-1 = 6, as selling price needs to be larger than buying price.
Example 2:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
*/

/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function(prices) {}

怎麼解

這題用 DP 會比較簡單,總共會有兩種方式一個是 hold 一種是 sell

dp = Array.from({length: n}, () ⇒ Array(2).fill(0))

  • hold (dp[i][0]): 之前就買的成本 vs 現在買的成本 選低的

  • sell(dp[i][1]): 現在賣 vs 之前賣 選高的

or

學到什麼

比最大最小值,可以先從以下開始

Last updated

Was this helpful?