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 get maximum value of power of a list by rearranging elements in Python
Given a list of positive numbers, we can move any single element to any position to maximize the list's power. The power of a list is calculated as the sum of (index + 1) × value_at_index for all indices.
$$\displaystyle\sum\limits_{i=0}^{n-1} (i+1)\times list[i]$$
For example, if nums = [6, 2, 3], we can move 6 to the end to get [2, 3, 6]. The power becomes: (2 × 1) + (3 × 2) + (6 × 3) = 26.
Algorithm
To solve this problem, we follow these steps ?
Create a prefix sum array
Pstarting with 0Calculate the base power (original arrangement)
For each element, try moving it to every possible position
Use the formula:
base + P[i] - P[j] - (i - j) * xto calculate new power efficientlyReturn the maximum power found
Implementation
class Solution:
def solve(self, nums):
# Create prefix sum array
P = [0]
base = 0
# Calculate base power and build prefix sum
for i, x in enumerate(nums, 1):
P.append(P[-1] + x)
base += i * x
ans = base
# Try moving each element to every position
for i, x in enumerate(nums):
for j in range(len(nums) + 1):
# Calculate power after moving element from i to j
ans = max(ans, base + P[i] - P[j] - (i - j) * x)
return ans
# Test the solution
ob = Solution()
nums = [6, 2, 3]
result = ob.solve(nums)
print(f"Input: {nums}")
print(f"Maximum power: {result}")
Input: [6, 2, 3] Maximum power: 26
How It Works
The algorithm uses a prefix sum array to efficiently calculate the power change when moving elements. When we move element x from position i to position j:
Elements between positions
iandjshift by one positionThe power change is calculated using:
P[i] - P[j] - (i - j) * xThis avoids recalculating the entire sum each time
Example Walkthrough
For nums = [6, 2, 3]:
Original power:
(6×1) + (2×2) + (3×3) = 19Moving 6 to the end:
(2×1) + (3×2) + (6×3) = 26This gives the maximum possible power of 26
Conclusion
This solution efficiently finds the maximum power by trying all possible single-element moves using prefix sums. The time complexity is O(n²) where n is the length of the input list.
