문제 설명
n개의 양의 정수가 있는 배열이 제공됩니다. 모든 요소를 동일하게 만들기 위한 최소 연산 수를 찾아야 합니다. 배열 요소의 모든 요소로 더하기, 곱하기, 빼기 또는 나누기를 수행할 수 있습니다.
예시
입력 배열이 {1, 2, 3, 4}이면 모든 요소를 동일하게 만들기 위해 최소 3번의 작업이 필요합니다. 예를 들어, 3개의 추가를 수행하여 요소 4를 만들 수 있습니다.
알고리즘
1. Select element with maximum frequency. Let us call it ‘x’ 2. Now we have to perform n-x operations as there are x element with same value
예시
#include
using namespace std;
int getMinOperations(int *arr, int n) {
unordered_map hash;
for (int i = 0;i < n; ++i) {
hash[arr[i]]++;
}
int maxFrequency = 0;
for (auto elem : hash) {
if (elem.second > maxFrequency) {
maxFrequency = elem.second;
}
}
return (n - maxFrequency);
}
int main() {
int arr[] = {1, 2, 3, 4};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Minimum required operations = " <<
getMinOperations(arr, n) << endl;
return 0;
} 위의 프로그램을 컴파일하고 실행할 때. 다음 출력을 생성합니다.
출력
Minimum required operations = 3