Sum of Total Strength of Wizards - 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 sum of all the individual strengths of the wizards in the group.
Return the sum of the total strengths of all contiguous groups of wizards. Since the answer may be very large, return it modulo 109 + 7.
A subarray is a contiguous non-empty sequence of elements within an array.
Input & Output
Example 1 — Basic Case
$
Input:
strength = [1,3,1,2]
›
Output:
42
💡 Note:
All subarrays: [1]=1×1=1, [1,3]=1×4=4, [1,3,1]=1×5=5, [1,3,1,2]=1×7=7, [3]=3×3=9, [3,1]=1×4=4, [3,1,2]=1×6=6, [1]=1×1=1, [1,2]=1×3=3, [2]=2×2=4. Total = 1+4+5+7+9+4+6+1+3+2 = 42
Example 2 — Single Element
$
Input:
strength = [5]
›
Output:
25
💡 Note:
Only one subarray [5]: minimum=5, sum=5, total strength = 5×5 = 25
Example 3 — Ascending Order
$
Input:
strength = [1,2,3]
›
Output:
44
💡 Note:
[1]=1×1=1, [1,2]=1×3=3, [1,2,3]=1×6=6, [2]=2×2=4, [2,3]=2×5=10, [3]=3×3=9. Total = 1+3+6+4+10+9 = 33
Constraints
- 1 ≤ strength.length ≤ 105
- 1 ≤ strength[i] ≤ 109
Visualization
Tap to expand
Understanding the Visualization
1
Input Array
Wizard strengths: [1,3,1,2]
2
Calculate Each Subarray
For each subarray: total_strength = min × sum
3
Sum All Results
Add all total_strength values together
Key Takeaway
🎯 Key Insight: Each element contributes as minimum to specific subarrays - find these ranges efficiently using monotonic stack
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code