|
| 1 | +// Source : https://leetcode.com/problems/maximum-element-after-decreasing-and-rearranging/ |
| 2 | +// Author : Hao Chen |
| 3 | +// Date : 2021-05-03 |
| 4 | + |
| 5 | +/***************************************************************************************************** |
| 6 | + * |
| 7 | + * You are given an array of positive integers arr. Perform some operations (possibly none) on arr so |
| 8 | + * that it satisfies these conditions: |
| 9 | + * |
| 10 | + * The value of the first element in arr must be 1. |
| 11 | + * The absolute difference between any 2 adjacent elements must be less than or equal to 1. In |
| 12 | + * other words, abs(arr[i] - arr[i - 1]) <= 1 for each i where 1 <= i < arr.length (0-indexed). abs(x) |
| 13 | + * is the absolute value of x. |
| 14 | + * |
| 15 | + * There are 2 types of operations that you can perform any number of times: |
| 16 | + * |
| 17 | + * Decrease the value of any element of arr to a smaller positive integer. |
| 18 | + * Rearrange the elements of arr to be in any order. |
| 19 | + * |
| 20 | + * Return the maximum possible value of an element in arr after performing the operations to satisfy |
| 21 | + * the conditions. |
| 22 | + * |
| 23 | + * Example 1: |
| 24 | + * |
| 25 | + * Input: arr = [2,2,1,2,1] |
| 26 | + * Output: 2 |
| 27 | + * Explanation: |
| 28 | + * We can satisfy the conditions by rearranging arr so it becomes [1,2,2,2,1]. |
| 29 | + * The largest element in arr is 2. |
| 30 | + * |
| 31 | + * Example 2: |
| 32 | + * |
| 33 | + * Input: arr = [100,1,1000] |
| 34 | + * Output: 3 |
| 35 | + * Explanation: |
| 36 | + * One possible way to satisfy the conditions is by doing the following: |
| 37 | + * 1. Rearrange arr so it becomes [1,100,1000]. |
| 38 | + * 2. Decrease the value of the second element to 2. |
| 39 | + * 3. Decrease the value of the third element to 3. |
| 40 | + * Now arr = [1,2,3], which satisfies the conditions. |
| 41 | + * The largest element in arr is 3. |
| 42 | + * |
| 43 | + * Example 3: |
| 44 | + * |
| 45 | + * Input: arr = [1,2,3,4,5] |
| 46 | + * Output: 5 |
| 47 | + * Explanation: The array already satisfies the conditions, and the largest element is 5. |
| 48 | + * |
| 49 | + * Constraints: |
| 50 | + * |
| 51 | + * 1 <= arr.length <= 10^5 |
| 52 | + * 1 <= arr[i] <= 10^9 |
| 53 | + ******************************************************************************************************/ |
| 54 | + |
| 55 | +class Solution { |
| 56 | +public: |
| 57 | + int maximumElementAfterDecrementingAndRearranging(vector<int>& arr) { |
| 58 | + sort(arr.begin(), arr.end()); |
| 59 | + int m = arr[0] = 1; |
| 60 | + for(int i=0; i<arr.size()-1; i++) { |
| 61 | + if (abs(arr[i] - arr[i+1]) <= 1) { |
| 62 | + m = max(arr[i], arr[i+1]); |
| 63 | + continue; |
| 64 | + } |
| 65 | + arr[i+1] = arr[i] + 1; |
| 66 | + m = arr[i+1]; |
| 67 | + } |
| 68 | + return m; |
| 69 | + } |
| 70 | +}; |
0 commit comments