Write a program to read a sequence of N integers and print the number that appears the maximum number of times in the sequence.
INPUT:
Input contains two lines. First line in the input indicates N, the number of integers in the sequence. Second line contains N integers, separated by white space.
OUTPUT:
Element with the maximum frequency. If two numbers have the same highest frequency, print the number that appears first in the sequence.
CONSTRAINTS:
1 <= N <= 10000
The integers will be in the range [-100,100].
Solution:
Input contains two lines. First line in the input indicates N, the number of integers in the sequence. Second line contains N integers, separated by white space.
OUTPUT:
Element with the maximum frequency. If two numbers have the same highest frequency, print the number that appears first in the sequence.
CONSTRAINTS:
1 <= N <= 10000
The integers will be in the range [-100,100].
Solution:
#include<stdio.h>
int main() {
int n, i, j;
scanf("%d", &n);
int arr[n];
for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
int freq = -1, maxEl = 0,tempFreq = 0;
for(i = 0; i < n; i++) {
//tempFreq stores the frequency of element arr[i] in the sequence
tempFreq = 0;
for(j = i; j < n; j++) {
//counting frequency of arr[i] only on the right side of i is enough; since if arr[i] occurred on left side of i, it’s frequency would have been more anyways
if (arr[i] == arr[j]) {
//if you encounter element equal to arr[i], increment tempFreq;
tempFreq++;
}
}
if (tempFreq > freq) {
//variable freq stores the maximum frequency that has been encountered so far
//maxEl stores the array element that has the maximum frequency encountered so far
freq = tempFreq; maxEl = arr[i];
}
}
printf("%d", maxEl);
}
int main() {
int n, i, j;
scanf("%d", &n);
int arr[n];
for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
int freq = -1, maxEl = 0,tempFreq = 0;
for(i = 0; i < n; i++) {
//tempFreq stores the frequency of element arr[i] in the sequence
tempFreq = 0;
for(j = i; j < n; j++) {
//counting frequency of arr[i] only on the right side of i is enough; since if arr[i] occurred on left side of i, it’s frequency would have been more anyways
if (arr[i] == arr[j]) {
//if you encounter element equal to arr[i], increment tempFreq;
tempFreq++;
}
}
if (tempFreq > freq) {
//variable freq stores the maximum frequency that has been encountered so far
//maxEl stores the array element that has the maximum frequency encountered so far
freq = tempFreq; maxEl = arr[i];
}
}
printf("%d", maxEl);
}
No comments:
Post a Comment