Problem
As the ruler of a kingdom, you have an army of wizards at your command.
You are given a 0-indexed integer array strength, where strength[i]
denotes the strength of the ith wizard. For a contiguous group of wizards (i.e. the wizards’ strengths form a subarray of strength), the
total strength is defined as the product of the following two values:
- The strength of the weakest wizard in the group.
- The total of all the individual strengths of the wizards in the group.
Return thesum of the total strengths of all contiguous groups of wizards. Since the answer may be very large, return it modulo 10^9 + 7.
A subarray is a contiguous non-empty sequence of elements within an array.
Examples
Example 1
| |
Example 2
| |
Constraints
1 <= strength.length <= 10^51 <= strength[i] <= 10^9
Solution
Method 1 - Monotonic Stack + Prefix Sums (Contribution by Minimum)
Intuition
For each element in strength we compute its contribution as the minimum across all subarrays where it is the minimum; summing these contributions gives the final answer. We use a monotonic stack to find the nearest smaller element to the left (left[i]) and the nearest smaller-or-equal to the right (right[i]) for every index i. To get the sum of subarray sums efficiently we maintain prefix sums pre and prefix-of-prefix sums ppre, then compute each element’s total contribution using those arrays and multiply by the element value. Use MOD for modulo arithmetic and accumulate into ans.
Approach
- Precompute
prewherepre[k]= sum ofstrength[0..k-1]moduloMOD. - Precompute
pprewhereppre[k]= sum ofpre[0..k-1]moduloMOD(prefix of prefix sums). - Use a monotonic increasing stack to compute
left[i]= index of previous smaller element for eachi(or-1if none). - Use a monotonic increasing stack (with >= for tie-breaking) from right to left to compute
right[i]= index of next smaller-or-equal element for eachi(ornif none). - For each index
i, letl = left[i]andr = right[i]. Usingppreandprewe compute the sum of all subarray sums whereiis the minimum astotal = ((ppre[r+1] - ppre[i+1]) * (i-l) - (ppre[i+1] - ppre[l+1]) * (r-i)) % MOD(adjusted to be positive). Multiplytotalbystrength[i]and add toansmoduloMOD. - Return
ans.
Code
| |
| |
| |
| |
| |
Complexity
- ⏰ Time complexity:
O(n) - 🧺 Space complexity:
O(n)