You are given an integer array consisting of elements. You can perform the following operations on an array :
- Choose any element and increase or decrease it by 3 for 1 coin.
- Choose any element and increase or decrease it by 2 for free.
You are required to spend the minimum number of coins in order to make all the elements in the array A equal.
Example:
Input: n = 4,arr[] = {3, 5, 2, 3};
Output: 1
Approach
Java
public class EqualElements {public static void main(String[] args){int n = 4;int arr[] = { 3, 5, 2, 3 };int cnt[] = new int[2];for (int i = 0; i < n; ++i) {++cnt[arr[i] & 1];}System.out.println(Math.min(cnt[0], cnt[1]));}}
C++
#include <bits/stdc++.h>using namespace std;int equalElement(int n, vector<int> arr){int odd = 0, even = 0;for (int i = 0; i < n; ++i){if (arr[i] % 2 == 0)even++;elseodd++;}return min(even, odd);}int main(){int n = 4;vector<int> arr = {3, 5, 2, 3};cout << equalElement(n, arr) << "\n";return 0;}
No comments:
Post a Comment