Max Subarr Product

Run Settings
LanguageJavaScript
Language Version
Run Command
var maxProductSubarray = function(nums) { let maxSubarrProd = 0; let [currMin, currMax] = [1, 1]; let start = 0; let end = 0; let maxStart = 0; let maxEnd = 0; for(let i = 0; i < nums.length; i++){ const num = nums[i]; const temp = num * currMax; if (temp < num && i > 0) { currMax = num; currMin = num; start = i; end = i; } else { currMax = Math.max(temp, currMin * num, num); currMin = Math.min(temp, currMin * num, num); if (currMax === num) { start = i; } end = i; } if (currMax > maxSubarrProd) { maxSubarrProd = currMax; maxStart = start; maxEnd = end; } } return { maxProduct: maxSubarrProd, startIndex: maxStart, endIndex: maxEnd, subarray: nums.slice(maxStart, maxEnd + 1) }; }; // Example usage: const nums = [2, 3, -2, 4]; const result = maxProductSubarray(nums); console.log(result);
Editor Settings
Theme
Key bindings
Full width
Lines