[LeetCode] 3375. Minimum Operations to Make Array Values Equal to K (Python)
난이도: Easy
Problem Description
You are given an integer array nums
and an integer k
.
An integer h
is called valid if all values in the array that are strictly greater than h
are identical.
For example, if nums = [10, 8, 10, 8]
, a valid integer is h = 9
because all nums[i] > 9
are equal to 10, but 5 is not a valid integer.
You are allowed to perform the following operation on nums
:
- Select an integer
h
that is valid for the current values innums
. - For each index
i
wherenums[i] > h
, setnums[i]
toh
.
Return the minimum number of operations required to make every element in nums
equal to k
. If it is impossible to make all elements equal to k
, return -1.
Problem Example
Example 1:
Input: nums = [5,2,5,4,5], k = 2
Output: 2
Explanation:
The operations can be performed in order using valid integers 4 and then 2.
Example 2:
Input: nums = [2,1,2], k = 2
Output: -1
Explanation:
It is impossible to make all the values equal to 2.
Example 3:
Input: nums = [9,7,5,3], k = 1
Output: 4
Explanation:
The operations can be performed using valid integers in the order 7, 5, 3, and 1.
Constraints
1 <= nums.length <= 100
1 <= nums[i] <= 100
1 <= k <= 100
✏️ Solution
class Solution:
def minOperations(self, nums: List[int], k: int) -> int:
if min(nums) < k:
return -1
nums = set(nums)
return len(nums) if k not in nums else len(nums)-1
문제를 읽었을 때 복잡해 보일 수 있지만, 좀만 생각해보면 쉽게 풀 수 있는 문제였다.
일단 nums의 최소값이 k보다 작으면 -1을 return한다.
그리고 nums의 요소를 중복을 없애기 위해 set으로 변환시켜주었다.
이 때, set 안에 k 값이 들어있으면 걔는 변환을 안시켜도 되기 때문에 len(nums)-1을 return하였고, k 값이 안들어 있다면 모두 변환해주어야 하기 때문에 len(nums)를 return 하여 정답을 맞을 수 있었다.
⚙️ Runtime & Memory
문제: 3375. Minimum Operations to Make Array Values Equal to K
깃허브: github
algorithmPractice/LeetCode/3621-minimum-operations-to-make-array-values-equal-to-k at main · laewonJeong/algorithmPractice
하루 한 문제 챌린지. Contribute to laewonJeong/algorithmPractice development by creating an account on GitHub.
github.com