LeetCode 2104: Sum of Subarray Ranges Solution

Master LeetCode problem 2104 (Sum of Subarray Ranges), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2104. Sum of Subarray Ranges

Problem Explanation

Explanation

To solve this problem, we need to calculate the sum of all subarray ranges of the given integer array nums. We can achieve this by iterating through the array and for each element, calculating the contribution of that element to the total sum of ranges. The contribution of an element nums[i] to the sum of ranges is (i+1)*(n-i)*nums[i], where n is the length of the array.

  1. Initialize a variable totalSum to store the total sum of ranges.
  2. Iterate through the array nums and for each element:
    • Calculate the contribution of that element to the total sum of ranges using the formula mentioned above.
    • Add the contribution to the totalSum.
  3. Return the totalSum.

Time Complexity: O(n), where n is the length of the input array nums. Space Complexity: O(1)

Solution Code

class Solution {
    public int sumSubarrayMins(int[] nums) {
        int MOD = (int)1e9 + 7;
        int n = nums.length;
        int totalSum = 0;

        for (int i = 0; i < n; i++) {
            totalSum = (totalSum + (i + 1) * (n - i) * nums[i]) % MOD;
        }

        return totalSum;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2104 (Sum of Subarray Ranges)?

This page provides optimized solutions for LeetCode problem 2104 (Sum of Subarray Ranges) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2104 (Sum of Subarray Ranges)?

The time complexity for LeetCode 2104 (Sum of Subarray Ranges) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2104 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2104 in Java, C++, or Python.

Back to LeetCode Solutions