Given an array of integers A, we need to calculate the sum of values for all possible subarrays, where each subarray’s value is defined as the difference between its maximum and minimum elements. The final sum should be computed modulo 10⁹ + 7.
The solution uses monotonic stacks to efficiently calculate how each element contributes to the final sum. Here’s a detailed breakdown:
These boundaries help us calculate how many subarrays include A[i] as their maximum or minimum.
max_contribution = (i - max_left[i]) × (max_right[i] - i) × A[i]
min_contribution = (i - min_left[i]) × (min_right[i] - i) × A[i]
The final contribution of each element is (max_contribution – min_contribution).
Consider the array A = [4, 7, 3, 8]
max_left = [-1, -1, 1, -1] // Index of nearest greater element on left
max_right = [ 1, 3, 3, 4] // Index of nearest greater element on right
min_left = [-1, 0, -1, 2] // Index of nearest smaller element on left
min_right = [ 2, 2, 4, 4] // Index of nearest smaller element on right
Similar calculations are performed for each element, and the results are summed modulo 10⁹ + 7.
The final result for this example is 26.
public class Solution {
public int solve(int[] A) {
int N = A.length;
Stack st = new Stack<>();
int[] max_left = new int[N];
for(int i = 0; i 0 && A[st.peek()] <= A[i]){
st.pop();
}
if(st.size() > 0){
max_left[i] = st.peek();
}
st.push(i);
}
int[] max_right = new int[N];
st = new Stack<>();
for(int i = N-1; i>=0; i--){
max_right[i] = N;
while(st.size() > 0 && A[st.peek()] < A[i]){
st.pop();
}
if(st.size() > 0){
max_right[i] = st.peek();
}
st.push(i);
}
// min left and right
int[] min_left = new int[N];
st = new Stack<>();
for(int i = 0; i 0 && A[st.peek()] >= A[i]){
st.pop();
}
if(st.size() > 0){
min_left[i] = st.peek();
}
st.push(i);
}
int[] min_right = new int[N];
st = new Stack<>();
for(int i = N-1; i>=0; i--){
min_right[i] = N;
while(st.size() > 0 && A[st.peek()] > A[i]){
st.pop();
}
if(st.size() > 0){
min_right[i] = st.peek();
}
st.push(i);
}
long ans = 0;
long MOD = 1000000007;
for(int i = 0; i
This approach efficiently computes the result without having to generate all possible subarrays explicitly, which would be inefficient for large arrays.
Our Program make you Job Ready for your Dream Company 🚀