
- 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 value for which given array expression is maximized in Python
Suppose we have two arrays called nums and values, both contains integers and the values of nums are strictly increasing and their lengths are also same. We have to find the value of v for a pair of indices i, j, such that: i ≤ j that maximizes v = values[i] + values[j] + nums[j] - nums[i].
So, if the input is like nums = [1, 2, 7] values = [-4, 6, 5], then the output will be 16, if we take pick i = 1 and j = 2 we get 6 + 5 + 7 - 2 = 16.
To solve this, we will follow these steps −
ans1 := -inf, ans2 := -inf
for i in range 0 to size of nums - 1, do
ans1 := maximum of ans1 and (values[i] - nums[i])
ans2 := maximum of ans2 and (values[i] + nums[i])
return ans1 + ans2
Example
Let us see the following implementation to get better understanding
from math import inf def solve(nums, values): ans1 = -inf ans2 = -inf for i in range(len(nums)): ans1 = max(ans1, (values[i] - nums[i])) ans2 = max(ans2, (values[i] + nums[i])) return ans1 + ans2 nums = [1, 2, 7] values = [-4, 6, 5] print(solve(nums, values))
Input
[1, 2, 7], [-4, 6, 5]
Output
16
- Related Articles
- Program to find maximum possible value of an expression using given set of numbers in Python
- Program to find expected value of given equation for random numbers in Python
- Program to find maximum value at a given index in a bounded array in Python
- Program to find smallest index for which array element is also same as index in Python
- 8086 program to find the min value in a given array
- Python Program to Construct an Expression Tree of a given Expression
- C++ program to find permutation for which sum of adjacent elements sort is same as given array
- C++ Program to Construct an Expression Tree for a given Prefix Expression
- Write a program in Python to find the index for NaN value in a given series
- Program to find array of length k from given array whose unfairness is minimum in python
- Program to find a pair (i, j) where nums[i] + nums[j] + (i -j) is maximized in Python?
- C++ program to find maximum possible value for which XORed sum is maximum
- Program to find maximum value of k for which we can maintain safe distance in Python
- Program to find expected value of maximum occurred frequency values of expression results in Python
- Program to find smallest string with a given numeric value in Python

Advertisements