[LeetCode] 121. Best Time to Buy and Sell Stock
5190 ワード
質問リンク
https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
コミットコード
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(prices) {
let max = 0
let result = 0
let arr = []
while (prices.length > 1) {
max = Math.max.apply(null, prices)
if (max === 0) { break }
arr = prices.slice(0, prices.findIndex((e) => e === max) + 1)
prices.splice(0, prices.findIndex((e) => e === max) + 1)
let arrMax = Math.max.apply(null, arr)
let arrMin = Math.min.apply(null, arr)
if (arrMax - arrMin > result) {
result = arrMax - arrMin
}
}
return result
};
解答方法
アレイ内の最大の数字を基準として,左側の最大,最小差を求める.
右側は、最大の数字に基づいて最大、最小の差を繰り返す過程で最大値を求める.
Reference
この問題について([LeetCode] 121. Best Time to Buy and Sell Stock), 我々は、より多くの情報をここで見つけました https://velog.io/@joohyun/LeetCode-121.-Best-Time-to-Buy-and-Sell-Stockテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol