C program to print the number of subset whose elements have difference 0 or 1

Here, we are going to learn how to print the number of subset whose elements have difference 0 or 1 using C program?
Submitted by Bhawna Aggarwal, on May 30, 2019

Given an array of integers, find and print the maximum number of integers you can select from the array such that the absolute difference between any two of the chosen integers is less than or equal to 1.

For example, if your array is a = [1,1,2,2,4,4,5,5,5]

You can create two subarrays meeting the criterion: [1,1,2,2] and [4,4,5,5,5]. The maximum length subarray has 5 elements.

Input format:

The first line contains a single integer a, the size of the array b.
The second line contains a space-separated integers b[i].

Output format:

A single integer denoting the maximum number of integers you can choose from the array such that the absolute difference between any two of the chosen integers is <=1.

Constraint:

2<=a<=100

Example:

Input:
    6
    4 6 5 3 3 1

    Output:
    3

Description:

We choose the following multiset of integers from the array:{4,3,3}. Each pair in the multiset has an absolute difference <=1(i.e., |4-3|=1 and |3-3|=0 ), So we print the number of chosen integers, 3 - as our answer.

Solution:

#include <stdio.h>
int main()
{
    //a is the length of array and b is the name of array.
    int a, t, i, j, count, k;
    count = 0;

    printf("Enter the size of the array: ");
    scanf("%d", &a);

    int b[a], d[101];

    printf("Enter array elements: ");
    for (i = 0; i < a; i++) {
        scanf("%d", &b[i]);
    }

    for (i = 0; i <= 100; i++) {
        for (j = 0; j < a; j++) {
            if (i == b[j]) {
                count = count + 1;
            }
        }
        d[i] = count;
        count = 0;
    }

    t = d[0] + d[1];

    for (i = 0; i < 100; i++) {
        k = d[i] + d[i + 1];
        if (k > t) {
            t = k;
        }
    }
    printf("Number of subset: %d", t);

    return 0;
}

Output

Enter the size of the array: 9
Enter array elements: 1 1 2 2 4 4 5 5 5
Number of subset: 5

C One-Dimensional Array Programs »



Related Programs




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.