# 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) {}

怎麼解

設初始值

min = Number.MAX_SAFE_INTEGER
max = 0

,for 迴圈比較找 max

min = Math.min(min, prices[i])
max = Math.max(max, prices[i] - min) 
var maxProfit = function(prices) {
  let min = Number.MAX_SAFE_INTEGER;
  let max = 0;
  for(let i = 0; len = prices.length, i<len; i++ ){
      min = Math.min(min, prices[i])
      max = Math.max(max, prices[i] - min)
  }
  return max;
};

學到什麼

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

min = Number.MAX_SAFE_INTEGER or 0 
max = Number.MIN_SAFE_INTEGER or 0

Last updated