[LeetCode] Sum of Total Strength of Wizards

2281. Sum of Total Strength of Wizards

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 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#define ll long long
#define vll vector<ll>

class Solution {
ll mod = 1e9 + 7;
ll res = 0;
public:
int totalStrength(vector<int>& A) {
ll n = A.size();
vll lpsum(n + 1, 0), lpmul(n + 1, 0);
vll rpsum(n + 1, 0), rpmul(n + 1, 0);
for(ll i = 0; i < n; i++) {
lpsum[i + 1] = (lpsum[i] + A[i]) % mod;
lpmul[i + 1] = (lpmul[i] + (i + 1) * A[i]) % mod;
}
for(ll i = n - 1; i>= 0; i--) {
rpsum[i] = (rpsum[i + 1] + A[i]) % mod;
rpmul[i] = (rpmul[i + 1] + (n - i) * A[i]) % mod;
}

vll st;
for(ll r = 0; r <= n; r++) {
while(!st.empty() and (r == n or A[st.back()] >= A[r])) {
ll pivot = st.back(); st.pop_back();
ll l = st.empty() ? 0 : st.back() + 1;
ll lsum = (mod + lpmul[pivot + 1] - lpmul[l] - l * (lpsum[pivot + 1] - lpsum[l])) % mod;
ll rsum = (mod + rpmul[pivot + 1] - rpmul[r] - (n - r) * (rpsum[pivot + 1] - rpsum[r])) % mod;
lsum = (lsum + mod) % mod;
rsum = (rsum + mod) % mod;

ll sum = (rsum * (pivot - l + 1) + lsum * (r - pivot)) % mod;
res = (res + sum * A[pivot]) % mod;
}

st.push_back(r);
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/22/PS/LeetCode/sum-of-total-strength-of-wizards/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.