06(June) Max sum in the configuration

06. Max Sum in the Configuration

The problem can be found at the following link: Question Link

Problem Description

Given an integer array a of size n, your task is to return the maximum value of the sum of i * a[i] for all 0 <= i <= n-1, where a[i] is the element at index i in the array. The only operation allowed is to rotate (clockwise or counterclockwise) the array any number of times.

Example:

Input:

n = 4, a[] = {8, 3, 1, 2}

Output:

29

Explanation: All the configurations possible by rotating the elements are:

  • 3 1 2 8 => sum is 30 + 11 + 22 + 83 = 29

  • 1 2 8 3 => sum is 10 + 21 + 82 + 33 = 27

  • 2 8 3 1 => sum is 20 + 81 + 32 + 13 = 17

  • 8 3 1 2 => sum is 80 + 31 + 12 + 23 = 11

So, the maximum sum will be 29.

My Approach

  1. Initialization:

    • Calculate the sum of all elements in the array and store it in sum.

    • Compute the initial value of currSum, which is the sum of i * a[i] for the array in its original configuration.

  2. Rotation Calculation:

    • Initialize maxi to store the maximum value of currSum.

    • Iterate through the array and calculate the value of currSum after each rotation. Update maxi if currSum after rotation is greater than the current maxi.

  3. Return:

    • Return maxi, which contains the maximum sum for the given configurations.

Time and Auxiliary Space Complexity

  • Expected Time Complexity: O(n), as we iterate through the array twice: once to compute the initial sums and once to calculate the rotated sums.

  • Expected Auxiliary Space Complexity: O(1), as we only use a constant amount of additional space.

Code (C++)

Code (Java)

Code (Python)

Contribution and Support

For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!

⭐ If you find this helpful, please give this repository a star! ⭐


📍Visitor Count

Last updated