Find Maximum Possible Value of an Expression in Python



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[1]/v[0] for each v in vs
  • best := 0
  • for i in range 0 to size of vs - 1, do
    • u := vs[i]
    • l := u[0]*u[0]+u[1]*u[1]
    • 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[0]+v[0], u[1]+v[1])
      • t2 := t1[0]*t1[0]+t1[1]*t1[1]
      • if t2 >= l, then
        • u := t1
        • l := t2
    • if l > best, then
      • best := l
    • u := vs[i]
    • l := u[0]*u[0]+u[1]*u[1]
    • 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[0]+v[0], u[1]+v[1])
      • t2 := t1[0]*t1[0]+t1[1]*t1[1]
      • 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[1],v[0]))

   best = 0
   for i in range(len(vs)):
      u = vs[i]
      l = u[0]*u[0]+u[1]*u[1]
      for v in (vs+vs)[i+1:(i+len(vs))]:
         t1 = (u[0]+v[0],u[1]+v[1])
         t2 = t1[0]*t1[0]+t1[1]*t1[1]
         if t2 >= l:
            u = t1
            l = t2
      if l > best:
         best = l
      u = vs[i]
      l = u[0]*u[0]+u[1]*u[1]
      for v in reversed((vs+vs)[i+1:(i+len(vs))]):
         t1 = (u[0]+v[0],u[1]+v[1])
         t2 = t1[0]*t1[0]+t1[1]*t1[1]
         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
Updated on: 2021-10-11T08:50:15+05:30

318 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements