Search for a command to run...
Try your own input
Change the array and replay the algorithm from step one.
Initialization
For each start i, extend the end j rightwards while tracking both the running minimum and running maximum, so each extension costs O(1).
Brute Force
1function subArrayRanges(arr) {2 const n = arr.length;3 let sum = 0;//n: 3sum: 04 for (let i = 0; i < n; i++) {5 let smallest = arr[i];6 let largest = arr[i];7 for (let j = i; j < n; j++) {8 smallest = Math.min(smallest, arr[j]);9 largest = Math.max(largest, arr[j]);10 sum += (largest - smallest);11 }12 }13 return sum;14}