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
Sum of Total Strength: [1,3,1,2]1312Single elements:[1]: min=1, sum=1 → 1×1=1[3]: min=3, sum=3 → 3×3=9[1]: min=1, sum=1 → 1×1=1[2]: min=2, sum=2 → 2×2=4Length 2 subarrays:[1,3]: min=1, sum=4 → 1×4=4[3,1]: min=1, sum=4 → 1×4=4[1,2]: min=1, sum=3 → 1×3=3Length 3 subarrays:[1,3,1]: min=1, sum=5 → 1×5=5[3,1,2]: min=1, sum=6 → 1×6=6Length 4 subarray:[1,3,1,2]: min=1, sum=7 → 1×7=7Total Strength = 1+9+1+4+4+4+3+5+6+7 = 44
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
Asked in
Google 15 Microsoft 12 Amazon 8
25.0K Views
Medium Frequency
~35 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen