Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find maximum element after decreasing and rearranging in Python
We are given an array and need to perform operations to satisfy these conditions:
The first element must be 1
The absolute difference between any two adjacent elements must be at most 1
We can perform two operations any number of times:
Decrease any value to a smaller positive number
Rearrange elements in any order
We need to find the maximum possible value after performing operations to satisfy the conditions.
Example
If the input is arr = [3,3,2,3,2], the output will be 3. We can decrease the last element to 1, then rearrange them like [1,2,3,3,3], and the maximum is 3.
Algorithm
To solve this problem, we follow these steps:
Sort the array in ascending order
Set the first element to 1
For each subsequent element, make it the minimum of its current value and the previous element + 1
Return the maximum element from the modified array
Implementation
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)
# Test with the given example
arr = [3, 3, 2, 3, 2]
result = solve(arr)
print(f"Maximum element after operations: {result}")
# Let's trace through the algorithm
arr_trace = [3, 3, 2, 3, 2]
print(f"Original array: {arr_trace}")
arr_trace.sort()
print(f"After sorting: {arr_trace}")
arr_trace[0] = 1
print(f"Set first element to 1: {arr_trace}")
for i in range(1, len(arr_trace)):
old_value = arr_trace[i]
arr_trace[i] = min(arr_trace[i - 1] + 1, arr_trace[i])
print(f"Step {i}: arr[{i}] = min({arr_trace[i-1]} + 1, {old_value}) = {arr_trace[i]}")
print(f"Final array: {arr_trace}")
print(f"Maximum value: {max(arr_trace)}")
Maximum element after operations: 3 Original array: [3, 3, 2, 3, 2] After sorting: [2, 2, 3, 3, 3] Set first element to 1: [1, 2, 3, 3, 3] Step 1: arr[1] = min(1 + 1, 2) = 2 Step 2: arr[2] = min(2 + 1, 3) = 3 Step 3: arr[3] = min(3 + 1, 3) = 3 Step 4: arr[4] = min(3 + 1, 3) = 3 Final array: [1, 2, 3, 3, 3] Maximum value: 3
How It Works
The algorithm works by first sorting the array to arrange elements optimally. Then it ensures the first element is 1 as required. For each subsequent position, it chooses the smaller value between the current element and the maximum allowed value (previous element + 1), ensuring the constraint is satisfied while maximizing the final result.
Conclusion
This greedy approach sorts the array and builds an optimal sequence starting from 1, ensuring adjacent differences are at most 1. The algorithm efficiently finds the maximum possible value in O(n log n) time complexity.
