Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

2281. Sum of Total Strength of Wizards

Explanation:

To solve this problem, we can iterate through all contiguous subarrays and calculate the total strength for each subarray according to the given formula. We can then sum up all these total strengths to get the final result.

  1. Initialize a variable result to store the total sum of strengths.
  2. Iterate over all possible subarrays:
    • For each subarray, calculate the total strength as the product of the minimum strength in the subarray and the sum of all strengths in the subarray.
    • Add this total strength to the result.
  3. Return the final result modulo 10^9 + 7 as the answer.

Time Complexity: O(n^2) where n is the number of wizards in the input array. Space Complexity: O(1)

:

class Solution {
    public int sumOfTotalStrength(int[] strength) {
        int mod = 1000000007;
        long result = 0;
        
        for (int i = 0; i < strength.length; i++) {
            long minStrength = strength[i];
            long sumStrength = 0;
            
            for (int j = i; j < strength.length; j++) {
                minStrength = Math.min(minStrength, strength[j]);
                sumStrength += strength[j];
                
                result = (result + minStrength * sumStrength) % mod;
            }
        }
        
        return (int) result;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.