# Program to find maximum possible value of an expression using given set of numbers in Python

PythonServer Side ProgrammingProgramming

Suppose we have two arrays called nums1 and nums2, they have same number of elements N. Now consider a set S with N elements from 1 through N. We have to find the value of (nums1[i1] + nums1[i2] + ... nums1[ik])^2 + (nums2[i1] + nums2[i2] + ... nums2[ik])^2 where {i1, i2, ... ik} is non empty subset of the set S.

So, if the input is like nums1 = [-1, 6] nums2 = [5, 4], then the output will be 106 because

• (-1)^2 + (5)^2 = 26
• (6)^2 + (4)^2 = 50
• (-1 + 6)^2 + (5 + 4)^2 = 106

To solve this, we will follow these steps −

• vs := a list of pairs (nums1[i], nums2[i]) for each i in range 0 to size of nums1 - 1
• vs := sort vs by tan-inverse of v/v for each v in vs
• best := 0
• for i in range 0 to size of vs - 1, do
• u := vs[i]
• l := u*u+u*u
• for each v in the concatenated list of vs and vs again from index i+1 to (i+ size of vs - 1), do
• t1 := (u+v, u+v)
• t2 := t1*t1+t1*t1
• if t2 >= l, then
• u := t1
• l := t2
• if l > best, then
• best := l
• u := vs[i]
• l := u*u+u*u
• for each v in reverse the concatenated list of vs and vs again from index i+1 to i+ size of vs -1], do
• t1 := (u+v, u+v)
• t2 := t1*t1+t1*t1
• if t2 >= l, then
• u := t1
• l := t2
• if l > best, then
• return best

## Example

Let us see the following implementation to get better understanding −

from math import atan2
def solve(nums1, nums2):
vs = zip(nums1,nums2)
vs = sorted(vs, key=lambda v: atan2(v,v))

best = 0
for i in range(len(vs)):
u = vs[i]
l = u*u+u*u
for v in (vs+vs)[i+1:(i+len(vs))]:
t1 = (u+v,u+v)
t2 = t1*t1+t1*t1
if t2 >= l:
u = t1
l = t2
if l > best:
best = l
u = vs[i]
l = u*u+u*u
for v in reversed((vs+vs)[i+1:(i+len(vs))]):
t1 = (u+v,u+v)
t2 = t1*t1+t1*t1
if t2 >= l:
u = t1
l = t2
if l > best:
best = l
return best

nums1 = [-1, 6]
nums2 = [5, -4]
print(solve(nums1, nums2))

## Input

[-1, 6], [5, -4]

## Output

52