Максимально возможные элементы, кратные 2
Дан целочисленный массив arr размера N. Задача состоит в том, чтобы найти максимально возможные элементы в массиве, которые делятся на 2 после модификации массива. Описанную ниже операцию можно выполнять произвольное количество раз (возможно, ноль раз).
Replace any two elements in the array with their sum.
Примеры:
Input : arr = [1, 2, 3, 1, 3]
Output : 3
After adding elements at index 0 and 2, and index 3 and 4, array becomes arr=[4, 2, 4].
Input : arr = [1, 2, 3, 4, 5]
Output : 3
After adding 1 and 3, array becomes arr=[4, 2, 4, 5].
Подход :
Во-первых, наблюдение состоит в том, что нам не нужно изменять элементы, которые делятся на 2 (т. Е. Четные числа). Потом мы ушли с нечетными числами. Сложение двух чисел даст четное число, которое делится на 2.
Итак, наконец, результат будет:
count_even + count_odd/2.
Below is the implementation of the above approach:
CPP
// CPP program to find maximum possible// elements which divisible by 2#include <bits/stdc++.h>using namespace std;// Function to find maximum possible// elements which divisible by 2int Divisible(int arr[], int n){ // To store count of even numbers int count_even = 0; for (int i = 0; i < n; i++) if (arr[i] % 2 == 0) count_even++; // All even numbers and half of odd numbers return count_even + (n - count_even) / 2;}// Driver codeint main(){ int arr[] = { 1, 2, 3, 4, 5 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call cout << Divisible(arr, n); return 0;} |
Java
// Java program to find maximum possible// elements which divisible by 2class GFG{ // Function to find maximum possible // elements which divisible by 2 static int Divisible(int arr[], int n) { // To store count of even numbers int count_even = 0; for (int i = 0; i < n; i++) if (arr[i] % 2 == 0) count_even++; // All even numbers and half of odd numbers return count_even + (n - count_even) / 2; } // Driver code public static void main (String[] args) { int arr[] = { 1, 2, 3, 4, 5 }; int n = arr.length; // Function call System.out.println(Divisible(arr, n)); }}// This code is contributed by AnkitRai01 |
Python3
# Python3 program to find maximum possible# elements which divisible by 2# Function to find maximum possible# elements which divisible by 2def Divisible(arr, n): # To store count of even numbers count_even = 0 for i in range(n): if (arr[i] % 2 == 0): count_even+=1 # All even numbers and half of odd numbers return count_even + (n - count_even) // 2# Driver codearr=[1, 2, 3, 4, 5]n = len(arr)# Function callprint(Divisible(arr, n))# This code is contribute by mohit kumar 29 |
C#
// C# program to find maximum possible// elements which divisible by 2using System;class GFG{ // Function to find maximum possible // elements which divisible by 2 static int Divisible(int []arr, int n) { // To store count of even numbers int count_even = 0; for (int i = 0; i < n; i++) if (arr[i] % 2 == 0) count_even++; // All even numbers and half of odd numbers return count_even + (n - count_even) / 2; } // Driver code static public void Main () { int []arr = { 1, 2, 3, 4, 5 }; int n = arr.Length; // Function call Console.Write(Divisible(arr, n)); }}// This code is contributed by ajit. |
Javascript
<script>// Javascript program to find maximum possible// elements which divisible by 2// Function to find maximum possible// elements which divisible by 2function Divisible(arr, n){ // To store count of even numbers let count_even = 0; for (let i = 0; i < n; i++) if (arr[i] % 2 == 0) count_even++; // All even numbers and half of odd numbers return count_even + parseInt((n - count_even) / 2);}// Driver code let arr = [ 1, 2, 3, 4, 5 ]; let n = arr.length; // Function call document.write(Divisible(arr, n));</script> |
3
Вниманию читателя! Не прекращайте учиться сейчас. Получите все важные математические концепции для соревновательного программирования с курсом Essential Maths for CP по доступной для студентов цене. Чтобы завершить подготовку от изучения языка к DS Algo и многому другому, см. Полный курс подготовки к собеседованию .