I am currently tackling the challenge of solving the Sum of Subarray Ranges
problem on LeetCode. Unfortunately, I am encountering a Time Limit Exceeded
error which suggests that my code might not be optimized efficiently enough. As I am still learning, I would appreciate some guidance on how to eliminate two nested for-loops
and replace them with just one in my implementation.
Question: Sum of Subarray Ranges
You have been given an integer array called nums. The range of a subarray within nums is defined as the difference between the largest and smallest elements present in that particular subarray. Your task is to calculate and return the sum of all subarray ranges within the given nums array. A subarray is essentially a contiguous non-empty sequence of elements from within an array.
Example:
Input: nums = [1,2,3]
Output: 4
Explanation: There are 6 subarrays for the given nums:
[1], range = largest - smallest = 1 - 1 = 0
[2], range = 2 - 2 = 0
[3], range = 3 - 3 = 0
[1,2], range = 2 - 1 = 1
[2,3], range = 3 - 2 = 1
[1,2,3], range = 3 - 1 = 2
Therefore, the sum of all ranges is 0 + 0 + 0 + 1 + 1 + 2 = 4.
Question link
My current code progress: Test cases passed so far: 52 out of 71
var subArrayRanges = function(nums) {
let maxSub=0;
for(let i=0; i<nums.length; i++){
let arr=[];
arr.push(nums[i])
for(let j=i+1; j<nums.length; j++){
arr.push(nums[j]);
maxSub=maxSub+(Math.max(...arr)) - (Math.min(...arr));
}
}
return maxSub
};
I am seeking advice on optimizing my code in order to ensure it passes all test cases successfully.