[英]calculating max - min within for loop
我嘗試做這個練習,其想法是,從一系列股票價值中,以較低的價值買入並以較高的價值賣出。
例子:
Input: [7,1,5,3,6,4]
Output: 5
解釋:
第 2 天買入(價格 = 1)並在第 5 天賣出(價格 = 6),利潤 = 6-1 = 5。
不是 7-1 = 6,因為賣價需要大於買價。
我試圖了解 for 循環在我發現的這個解決方案中是如何工作的:
var maxProfit = function(prices) {
let profit = 0;
let min = Number.MAX_SAFE_INTEGER;
for(let i = 0; i < prices.length; i++) {
min = Math.min(min, prices[i]);
profit = Math.max(profit, prices[i] - min);
}
return profit
}
有以下數組[7,1,5,3,6,4]
,我知道:
min = Math.min(min, prices[i]); = 1
但我不明白為什么這條線: profit = Math.max(profit, prices[i] - min);
知道在找到最小值后只減去數組的較高值 6-1
當我輸入 min 變量返回的數字 1 時,如下所示: profit = Math.max(profit, prices[i] - 1);
它轉到數組的開頭並執行 7-1。
我希望我的問題是有意義的。 我對循環如何在這里運行感到非常困惑。
謝謝
profit = 0; //init
profit = Math.Max(0,7-7)//i=0; profit = 0
profit = Math.Max(0,1-1)//i=1; profit = 0
profit = Math.Max(0,5-1)//i=2; profit = 4
profit = Math.Max(4,3-1)//i=3; profit = 4
profit = Math.Max(4,6-1)//i=4; profit = 5
profit = Math.Max(5,4-1)//i=5; profit = 5
我認為您真的希望這樣做:
function maxProfit(prices, startDay = 1){ const p = prices.slice(startDay-1); return Math.max(...p)-Math.min(...p); } const nums = [7, 1, 5, 3, 6, 4]; console.log(maxProfit(nums, 2));
當然,我個人會 go 第一天的索引為零,但這就是你想要的......我想。
閱讀有關console.log
和調試的信息。
這個:
min = Math.min(min, prices[i]);
不等於1 ,它取決於i 、 min和價格數組。
分析下面腳本的output:
var maxProfit = function(prices) { let profit = 0; let min = Number.MAX_SAFE_INTEGER; for(let i = 0; i < prices.length; i++) { min = Math.min(min, prices[i]); profit = Math.max(profit, prices[i] - min); console.log("i: ", i, " price: ", prices[i], " min: ", min, " profit: ", profit); } return profit } var prices = [7,1,5,3,6,4]; maxProfit(prices);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.