
- 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 sum of multiplied numbers in Python
Suppose we have two lists called nums and multipliers. Now consider an operation where we can remove any number from nums and remove any number from multipliers then multiply them together. We must repeat this operation until one of the lists is empty, we have to find the maximum sum of the multiplied numbers.
So, if the input is like nums = [-4, 4, 3] multipliers = [-2, 2], then the output will be 16, as We can match -4 with -2 and 4 with 2 to get -4 * -2 + 4 * 2.
To solve this, we will follow these steps −
sort the list nums
sort the list multipliers
res := 0
if size of nums < size of multipliers, then
swap nums and multipliers := multipliers, nums
n := size of nums
m := size of multipliers
for i in range 0 to m - 1, do
if multipliers[i] <= 0, then
res := res + nums[i] * multipliers[i]
otherwise,
res := res + multipliers[i] * nums[n -(m - i)]
return res
Example
Let us see the following implementation to get better understanding
def solve(nums, multipliers): nums.sort() multipliers.sort() res = 0 if len(nums) < len(multipliers): nums, multipliers = multipliers, nums n, m = len(nums), len(multipliers) for i in range(m): if multipliers[i] <= 0: res += nums[i] * multipliers[i] else: res += multipliers[i] * nums[n - (m - i)] return res nums = [-4, 4, 3] multipliers = [-2, 2] print(solve(nums, multipliers))
Input
[-4, 4, 3], [-2, 2]
Output
16
- Related Articles
- Program to find maximum sum by removing K numbers from ends in python
- Program to find sum of contiguous sublist with maximum sum in Python
- Python program to find the maximum of three numbers
- 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
- Program to find maximum ascending subarray sum using Python
- Program to find maximum sum of two non-overlapping sublists in Python
- Program to find sum of first N odd numbers in Python
- Program to find maximum weighted sum for rotated array in Python
- Program to find maximum additive score by deleting numbers in Python
- Program to find the sum of first n odd numbers in Python
- Program to find maximum sum of non-adjacent nodes of a tree in Python
- Java program to find maximum of three numbers
- Program to find maximum sum by flipping each row elements in Python
