
- 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 find maximum weighted sum for rotated array in Python
Suppose we have an array of few elements. We shall have to find the maximum weighted sum if the array elements are rotated. The weighted sum of an array nums can be calculated like below −
$$\mathrm{𝑆=\sum_{\substack{𝑖=1}}^{n}𝑖∗𝑛𝑢𝑚𝑠[𝑖]}$$
So, if the input is like L = [5,3,4], then the output will be 26 because
array is [5,3,4], sum is 5 + 2*3 + 3*4 = 5 + 6 + 12 = 23
array is [3,4,5], sum is 3 + 2*4 + 3*5 = 3 + 8 + 15 = 26 (maximum)
array is [4,5,3], sum is 4 + 2*5 + 3*3 = 4 + 10 + 9 = 23
To solve this, we will follow these steps −
- n := size of nums
- sum_a := sum of all elements in nums
- ans := sum of all elements of (nums[i] *(i + 1)) for all i in range 0 to n
- cur_val := ans
- for i in range 0 to n - 1, do
- cur_val := cur_val - sum_a + nums[i] * n
- ans := maximum of ans and cur_val
- return ans
Example
Let us see the following implementation to get better understanding −
def solve(nums): n = len(nums) sum_a = sum(nums) cur_val = ans = sum(nums[i] * (i + 1) for i in range(n)) for i in range(n): cur_val = cur_val - sum_a + nums[i] * n ans = max(ans, cur_val) return ans nums = [5,3,4] print(solve(nums))
Input
[5,3,4]
Output
26
- Related Articles
- Partition Array for Maximum Sum in Python
- Program to find the maximum number in rotated list in C++
- JavaScript Program for Maximum equilibrium sum in an array
- Program to find maximum in generated array in Python
- Program to find sum of contiguous sublist with maximum sum in Python
- Program to find maximum sum of multiplied numbers in Python
- Program to find maximum ascending subarray sum using Python
- Program to check whether an array Is sorted and rotated in Python
- Program to find the maximum sum of circular sublist in Python
- Program to find maximum sum obtained of any permutation in Python
- Program to find maximum absolute sum of any subarray in Python
- Python Program to find the sum of array
- Maximum element in a sorted and rotated array in C++
- C++ program to find maximum possible value for which XORed sum is maximum
- Search in Rotated Sorted Array in Python

Advertisements