Syntax error Program to find max value of an equation in Python

Program to find max value of an equation in Python



Suppose we have an array called points containing the coordinate points on a 2D plane, they are sorted by the x-values, where points[i] = (x_i, y_i) so x_i < x_j for all 1 <= i < j <= number of points. We also have another value k. We have to find the maximum value of the equation y_i + y_j + |x_i - x_j| where |x_i - x_j| <= k and 1 <= i < j <= number of points.

So, if the input is like points = [[2,4],[3,1],[6,11],[7,-9]] k = 1, then the output will be 6 because the first two points satisfy the condition |xi - xj| <= 1 now if we calculate the equation we get 4 + 1 + |2 - 3| = 6. Third and fourth points also satisfy the condition and returns a value of 11 + -9 + |6 - 7| = 3, so maximum is 6.

To solve this, we will follow these steps −

  • left := 0, right := 1

  • max_value := -inf

  • while right < size of points, do

    • (xl, yl) := points[left]

    • (xr, yr) := points[right]

    • diff := |xr - xl|

    • if left is same as right, then

      • right := right + 1

    • otherwise when diff <= k, then

      • m := yl + yr + diff

      • max_value := maximum of max_value and m

      • if yl >= yr - diff, then

        • right := right + 1

      • otherwise,

        • left := left + 1

      • otherwise,

        • left := left + 1

  • return max_value

Example

Let us see the following implementation to get better understanding

def solve(points, k):
   left, right = 0, 1
   max_value = float('-inf')

   while right < len(points):
      xl, yl = points[left]
      xr, yr = points[right]

      diff = abs(xr - xl)
      if left == right:
         right += 1
      elif diff <= k:
         m = yl + yr + diff
         max_value = max(max_value, m)
         if yl >= yr - diff:
            right += 1
         else:
            left += 1
      else:
         left += 1

   return max_value

points = [[2,4],[3,1],[6,11],[7,-9]]
k = 1
print(solve(points, k))

Input

[[2,4],[3,1],[6,11],[7,-9]], 1

Output

6
Updated on: 2021-10-06T08:36:30+05:30

534 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements