githubEdit

23. Minimize the Heights I

The problem can be found at the following link: Problem Linkarrow-up-right

✨ LeetCode Problem of the Day (POTD) Solutions ✨

LeetCode POTD Solution arrow-up-rightSolutions Up-to-Datearrow-up-right

Problem Description

Given a positive integer k and an array arr[] denoting the heights of towers, you are allowed to modify the height of each tower either by increasing or decreasing them by k only once. Your task is to find the possible minimum difference between the height of the shortest and the longest towers after modification.

Note: A slight modification of the problem can be found herearrow-up-right.

Examples:

Input: k = 2, arr[] = [1, 5, 8, 10] Output: 5 Explanation: The array can be modified as [3, 3, 6, 8]. The difference between the largest and smallest heights is 8 - 3 = 5.

Input: k = 3, arr[] = [3, 9, 12, 16, 20] Output: 11 Explanation: The array can be modified as [6, 12, 9, 13, 17]. The difference between the largest and smallest heights is 17 - 6 = 11.

Constraints:

  • 1 ≤ k ≤ 10^4

  • 1 ≤ number of towers ≤ 10^5

  • 0 ≤ arr[i] ≤ 10^5

My Approach

  1. Sorting Approach: The idea is to first sort the array and then attempt to modify the heights in such a way that the difference between the tallest and shortest towers is minimized. By modifying the tallest and shortest towers with either an addition or subtraction of k, we minimize the range. The goal is to iterate through the modified array to find the minimum possible difference.

  2. Steps:

    • Sort the array to bring the shortest and tallest towers together.

    • Adjust the smallest and largest elements with either addition or subtraction of k.

    • Use a sliding window approach to minimize the difference between the largest and smallest heights after modification.

Time and Auxiliary Space Complexity

  • Expected Time Complexity: O(n log n), where n is the size of the array. Sorting the array takes O(n log n), and subsequent linear passes over the array take O(n).

  • Expected Auxiliary Space Complexity: O(n), as we use additional space to store the modified tower heights and count arrays.

Code (C++)

Code (Java)

Code (Python)

Contribution and Support

For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questionsarrow-up-right. Let’s make this learning journey more collaborative!

⭐ If you find this helpful, please give this repository a star! ⭐


📍Visitor Count

Last updated