We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Maximum Element After Decreasing and Rearranging

Number: 1956

Difficulty: Medium

Paid? No

Companies: Amazon


Problem Description

Given an array of positive integers, we are allowed to rearrange the array and decrease any element to a smaller positive integer. The objective is to have the first element equal to 1 and ensure that the absolute difference between any two adjacent elements is at most 1. Under these operations, determine the maximum possible value of any element in the array.


Key Insights

  • Rearrangement means we can sort the array in non-decreasing order.
  • Starting with a value of 1 at the first index sets the base condition.
  • For each subsequent element, the optimal strategy is to set its value to the minimum between its current (or sorted) value and one more than the previous element.
  • This greedy approach guarantees that the differences between adjacent elements never exceed 1 while maximizing the final element.

Space and Time Complexity

Time Complexity: O(n log n) due to sorting the array, plus O(n) for processing. Space Complexity: O(n) for storing the sorted array (or O(1) if sorting in-place).


Solution

The solution leverages a greedy algorithm. First, the array is sorted so that we can build the optimal consecutive sequence from the smallest available values. We initialize the first element to 1 as required. Then, for every subsequent position i (from 1 to n-1), we assign arr[i] = min(sorted_arr[i], arr[i-1] + 1) ensuring the adjacent difference condition is met. The final maximum element is the last element in this modified list.

Data structures: A list (array) is used. Algorithmic approach: Sorting followed by a single pass through the sorted list with a greedy update for consecutive differences.


Code Solutions

# Python solution with line-by-line comments

def maximum_element_after_decreasing(arr):
    # Step 1: Sort the array to facilitate optimal rearrangement
    arr.sort()
    
    # Step 2: Set the first element to 1 as required
    current_max = 1
    
    # Step 3: Iterate through the sorted array starting from index 1
    for i in range(1, len(arr)):
        # Update the current element to be the minimum between the current value in arr
        # and one more than the previous maximum value
        current_max = min(arr[i], current_max + 1)
    
    # The variable current_max now holds the maximum possible value after operations
    return current_max

# Example usage:
# arr = [2,2,1,2,1]
# print(maximum_element_after_decreasing(arr))  # Output: 2
← Back to All Questions