Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find maximum weighted sum for rotated array in Python
When we have an array and need to find the maximum weighted sum after rotating it, we calculate the sum where each element is multiplied by its position (1-indexed). The weighted sum formula is:
$$\mathrm{S=\sum_{i=0}^{n-1}(i+1) \times nums[i]}$$
For example, with array [5,3,4], we need to check all possible rotations and find the maximum weighted sum.
Understanding the Problem
Let's see how weighted sum works for array L = [5,3,4]:
Original array [5,3,4]: sum = 1×5 + 2×3 + 3×4 = 5 + 6 + 12 = 23
Rotated array [3,4,5]: sum = 1×3 + 2×4 + 3×5 = 3 + 8 + 15 = 26 (maximum)
Rotated array [4,5,3]: sum = 1×4 + 2×5 + 3×3 = 4 + 10 + 9 = 23
Algorithm
Instead of generating all rotations, we use an efficient approach:
- Calculate initial weighted sum
- For each rotation, update the sum using a mathematical formula
- Track the maximum sum encountered
Implementation
def solve(nums):
n = len(nums)
sum_a = sum(nums)
# Calculate initial weighted sum
cur_val = ans = sum(nums[i] * (i + 1) for i in range(n))
# Check all rotations
for i in range(n):
cur_val = cur_val - sum_a + nums[i] * n
ans = max(ans, cur_val)
return ans
# Test with example
nums = [5, 3, 4]
result = solve(nums)
print(f"Array: {nums}")
print(f"Maximum weighted sum: {result}")
Array: [5, 3, 4] Maximum weighted sum: 26
How It Works
The algorithm uses a key insight: when we rotate an array left by one position, the weighted sum changes predictably. Each element's contribution decreases by the element's value, except the first element which moves to the end and gets multiplied by n.
Step-by-Step Example
def solve_with_steps(nums):
n = len(nums)
sum_a = sum(nums)
# Initial weighted sum
cur_val = sum(nums[i] * (i + 1) for i in range(n))
ans = cur_val
print(f"Initial array: {nums}")
print(f"Initial weighted sum: {cur_val}")
print()
for i in range(n):
cur_val = cur_val - sum_a + nums[i] * n
ans = max(ans, cur_val)
# Show the rotation
rotated = nums[i+1:] + nums[:i+1]
print(f"Rotation {i+1}: {rotated}")
print(f"Weighted sum: {cur_val}")
print()
return ans
nums = [5, 3, 4]
result = solve_with_steps(nums)
print(f"Maximum weighted sum: {result}")
Initial array: [5, 3, 4] Initial weighted sum: 23 Rotation 1: [3, 4, 5] Weighted sum: 26 Rotation 2: [4, 5, 3] Weighted sum: 23 Rotation 3: [5, 3, 4] Weighted sum: 23 Maximum weighted sum: 26
Time Complexity
The solution runs in O(n) time complexity, making it efficient for large arrays. Space complexity is O(1) as we only use a few variables.
Conclusion
This algorithm efficiently finds the maximum weighted sum by using mathematical insight instead of generating all rotations. The key is understanding how the weighted sum changes with each rotation.
