
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to get maximum value of power of a list by rearranging elements in Python
Suppose we have a list nums of N positive numbers. Now we can select any single value from the list, and move (not swap) it to any position. We can also not move any to position at all. So we have to find what is the maximum possible final power of the list? As we know the power of a list is the sum of (index + 1) * value_at_index over all indices i.
$$\displaystyle\sum\limits_{i=0}^{n-1} (i+1)\times list[i]$$
So, if the input is like nums = [6, 2, 3], then the output will be 26, as we can move the 6 to the end to get list [2, 3, 6] so the power is: (2 * 1) + (3 * 2) + (6 * 3) = 26.
To solve this, we will follow these steps −
P := a list with value 0
base := 0
for each index i and value x of A, do
insert last element of P + x at the end of P
base := base + (i+1) * x
ans := base
for each index i and value x in A, do
for j in range 0 to size of A + 1, do
ans := maximum of ans and (base + P[i] - P[j] -(i - j) * x)
return ans
Example
Let us see the following implementation to get a better understanding −
class Solution: def solve(self, A): P = [0] base = 0 for i, x in enumerate(A, 1): P.append(P[-1] + x) base += i * x ans = base for i, x in enumerate(A): for j in range(len(A) + 1): ans = max(ans, base + P[i] - P[j] - (i - j) * x) return ans ob = Solution() nums = [6, 2, 3] print(ob.solve(nums))
Input
[6, 2, 3]
Output
26
- Related Articles
- Program to Find Out the Maximum Final Power of a List in Python
- Python program to get maximum of each key Dictionary List
- Program to find maximum element after decreasing and rearranging in Python
- Get first element with maximum value in list of tuples in Python
- Program to find maximum sum of popped k elements from a list of stacks in Python
- Program to get indices of a list after deleting elements in ascending order in Python
- Python program to compute the power by Index element in List
- Program to find out the value of a power of 2 in Python
- Program to get maximum profit by scheduling jobs in Python
- List all the numbers by rearranging the digits of 1546.
- Get first and last elements of a list in Python
- Rearranging elements of an array in JavaScript
- Find elements of a list by indices in Python
- Program to find maximum value we can get in knapsack problem by taking multiple copies in Python
- Python program to find sum of elements in list
