907. Sum of Subarray Minimums
by Botao Xiao
Question
Given an array of integers A, find the sum of min(B), where B ranges over every (contiguous) subarray of A.
Since the answer may be large, return the answer modulo 10^9 + 7.
Example 1:
Input: [3,1,2,4]
Output: 17
Explanation: Subarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4].
Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1. Sum is 17.
Note:
- 1 <= A.length <= 30000
- 1 <= A[i] <= 30000
Solution
- Method 1: Brutal force O(N^2)
class Solution { public int sumSubarrayMins(int[] A) { if(A == null || A.length == 0) return 0; long sum = 0; for(int i = 0; i < A.length; i++){ int min = A[i]; for(int j = i; j < A.length; j++){ min = Math.min(A[j], min); sum += min; } } return (int)(sum % (Math.pow(10, 9) + 7)); } }
Subscribe via RSS