Program to find maximum element after decreasing and rearranging in Python


Suppose we have an array called arr. We have to perform some operations on arr so that it satisfies these conditions −

  • The first element in arr must be 1.

  • The absolute difference between any 2 adjacent elements must be at most 1.

And there are two operations. We can perform these two types of operations any number of times −

  • Decrease any value of arr to a smaller positive number.

  • Rearrange the elements of arr to be in any order.

We have to find the maximum possible value in arr after performing the operations to satisfy the given conditions.

So, if the input is like arr = [3,3,2,3,2], then the output will be 3 because, we can decrease the last element to 1, then rearrange them like [1,2,3,3,3], and maximum is 3.

To solve this, we will follow these steps −

  • sort the list arr

  • arr[0] := 1

  • for i in range 1 to size of arr - 1, do

    • arr[i] := minimum of (arr[i - 1] + 1) and arr[i]

  • return maximum of arr

Example

Let us see the following implementation to get better understanding −

def solve(arr):
   arr.sort()
   arr[0] = 1

   for i in range(1, len(arr)):
      arr[i] = min(arr[i - 1] + 1, arr[i])

   return max(arr)

arr = [3,3,2,3,2]
print(solve(arr))

Input

[3,3,2,3,2]

Output

3

Updated on: 08-Oct-2021

124 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements