반응형

https://leetcode.com/problems/maximum-element-after-decreasing-and-rearranging/description

 

Maximum Element After Decreasing and Rearranging - LeetCode

Can you solve this real interview question? Maximum Element After Decreasing and Rearranging - You are given an array of positive integers arr. Perform some operations (possibly none) on arr so that it satisfies these conditions: * The value of the first e

leetcode.com

 

arr을 오름차순으로 정렬해주고, 0번째 값을 1로 바꿔줍니다.

i(i > 0)번째 값부터는, arr[i] = min(arr[i], arr[i - 1] + 1).

arr[i]가 arr[i - 1] + 1보다 더 큰 값일 수 있다면, 차감 연산을 수행해줍니다.

class Solution {
public:
    int maximumElementAfterDecrementingAndRearranging(vector<int>& arr) {
        sort(arr.begin(), arr.end());
        arr[0] = 1;
        for(int i=1; i<arr.size(); i++) {
            arr[i] = min(arr[i], arr[i - 1] + 1);
        }
        return arr.back();
    }
};
반응형

'Algorithm' 카테고리의 다른 글

LeetCode 1980. Find Unique Binary String  (0) 2023.11.17
LeetCode 15. 3Sum  (0) 2023.11.15
LeetCode 1930. Unique Length-3 Palindromic Subsequences  (1) 2023.11.14
LeetCode 2785. Sort Vowels in a String  (1) 2023.11.13
LeetCode 815. Bus Routes  (1) 2023.11.12

+ Recent posts