Class Solution

java.lang.Object
g2101_2200.s2104_sum_of_subarray_ranges.Solution

public class Solution extends Object
2104 - Sum of Subarray Ranges.<p>Medium</p> <p>You are given an integer array <code>nums</code>. The <strong>range</strong> of a subarray of <code>nums</code> is the difference between the largest and smallest element in the subarray.</p> <p>Return <em>the <strong>sum of all</strong> subarray ranges of</em> <code>nums</code><em>.</em></p> <p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p> <p><strong>Example 1:</strong></p> <p><strong>Input:</strong> nums = [1,2,3]</p> <p><strong>Output:</strong> 4</p> <p><strong>Explanation:</strong> The 6 subarrays of nums are the following:</p> <p>[1], range = largest - smallest = 1 - 1 = 0</p> <p>[2], range = 2 - 2 = 0</p> <p>[3], range = 3 - 3 = 0</p> <p>[1,2], range = 2 - 1 = 1</p> <p>[2,3], range = 3 - 2 = 1</p> <p>[1,2,3], range = 3 - 1 = 2</p> <p>So the sum of all ranges is 0 + 0 + 0 + 1 + 1 + 2 = 4.</p> <p><strong>Example 2:</strong></p> <p><strong>Input:</strong> nums = [1,3,3]</p> <p><strong>Output:</strong> 4</p> <p><strong>Explanation:</strong> The 6 subarrays of nums are the following:</p> <p>[1], range = largest - smallest = 1 - 1 = 0</p> <p>[3], range = 3 - 3 = 0</p> <p>[3], range = 3 - 3 = 0</p> <p>[1,3], range = 3 - 1 = 2</p> <p>[3,3], range = 3 - 3 = 0</p> <p>[1,3,3], range = 3 - 1 = 2</p> <p>So the sum of all ranges is 0 + 0 + 0 + 2 + 0 + 2 = 4.</p> <p><strong>Example 3:</strong></p> <p><strong>Input:</strong> nums = [4,-2,-3,4,1]</p> <p><strong>Output:</strong> 59</p> <p><strong>Explanation:</strong> The sum of all subarray ranges of nums is 59.</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 <= nums.length <= 1000</code></li> <li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li> </ul> <p><strong>Follow-up:</strong> Could you find a solution with <code>O(n)</code> time complexity?</p>
  • Constructor Details

    • Solution

      public Solution()
  • Method Details

    • subArrayRanges

      public long subArrayRanges(int[] nums)