#2281

Sum of Total Strength of Wizards

Hard
ArrayStackMonotonic StackPrefix SumMonotonic StackPrefix SumSliding Window
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution leverages the concept of prefix sums and a monotonic stack to efficiently calculate the contribution of each wizard to the total strength across all subarrays they are part of. This reduces the number of operations significantly.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a prefix sum array to store cumulative sums of strengths.
  2. 2Step 2: Use a monotonic stack to determine the next and previous smaller elements for each wizard's strength.
  3. 3Step 3: For each wizard, calculate their contribution to the total strength using the prefix sums and the indices from the monotonic stack.
solution.py21 lines
1def totalStrength(strength):
2    MOD = 10**9 + 7
3    n = len(strength)
4    prefix_sum = [0] * (n + 1)
5    for i in range(n):
6        prefix_sum[i + 1] = (prefix_sum[i] + strength[i]) % MOD
7    stack = []
8    total_sum = 0
9    for i in range(n):
10        while stack and strength[stack[-1]] > strength[i]:
11            j = stack.pop()
12            k = stack[-1] if stack else -1
13            total_sum += strength[j] * (prefix_sum[i] - prefix_sum[k + 1]) * (j - k) % MOD
14            total_sum %= MOD
15        stack.append(i)
16    while stack:
17        j = stack.pop()
18        k = stack[-1] if stack else -1
19        total_sum += strength[j] * (prefix_sum[n] - prefix_sum[k + 1]) * (j - k) % MOD
20        total_sum %= MOD
21    return total_sum

Complexity note: The optimal solution runs in linear time due to the use of a monotonic stack, which allows us to efficiently find the contribution of each wizard without recalculating sums for overlapping subarrays.

  • 1Each wizard's strength contributes to multiple subarrays, and we can calculate this contribution efficiently.
  • 2Using prefix sums allows us to avoid recalculating sums for overlapping subarrays.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.