# Leetcode 2281 Sum of Total Strength of Wizards Solution in java | Hindi Coding Community

0

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.

Example 1:

Input: strength = [1,3,1,2]

Output: 44

public int totalStrength(int[] A) {
int res = 0, ac = 0, mod = (int)1e9 + 7, n = A.length;
Stack<Integer> stack = new Stack<>();
int[] acc = new int[n + 2];
for (int r = 0; r <= n; ++r) {
int a = r < n ? A[r] : 0;
ac = (ac + a) % mod;
acc[r + 1] = (ac + acc[r]) % mod;
while (!stack.isEmpty() && A[stack.peek()] > a) {
int i = stack.pop();
int l = stack.isEmpty() ? -1 : stack.peek();
long lacc = l < 0 ? acc[i] : acc[i] - acc[l], racc = acc[r] - acc[i];
int ln = i - l, rn = r - i;
res = (int)(res + (racc * ln - lacc * rn) % mod * A[i] % mod) % mod;
}
stack.push(r);
}
return (res + mod) % mod;
}