Program to find value for which given array expression is maximized in Python

PythonServer Side ProgrammingProgramming

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
raja
Updated on 11-Oct-2021 08:01:04

Advertisements