Max among K-Set
Max among K-Set
PROBLEM STATEMENT :
The program must accept N integers and an integer K as the input. The program must print the maximum among each set of integers of size K. If the last set does not contain K integers, then ignore the set.
Boundary Condition(s):
1 <= K <= N <= 100
1 <= Each integer value <= 10^5
Input Format:
The first line contains N.
The second line contains N integer values separated by a space.
The third line contains K.
Output Format:
The first line contains the integer values separated by a space.
Example Input/Output 1:
Input: ()
10
2 55 88 14 678 455 9899 12 545 222
4
Output:
88 9899
Explanation:
Here N = 10 and K = 4.
The maximum integer among the first 4 integers is 88 (2, 55, 88, 14). So 88 is printed.
The maximum integer among the next 4 integers is 9899 (678, 455, 9899, 12).
So 9899 is printed. The last set contains only two integers, so the last set is ignored.
Example Input/Output 2:
Input: ()
10
2 55 88 14 678 455 9899 12 545 222
5
Output:
678 9899
1) LEARN THRICE
👇
2) THINK TWICE
👇
3) APPLY ONCE
SOLUTION :
C (Programming Language)
#include<stdio.h>
#include<stdlib.h>
int main()
{
int n,k,max=0;
scanf("%d",&n);
int i,a[n];
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
scanf(" %d ",&k);
for(i=0;i<n;i++)
{
if(max<a[i])
max=a[i];
if((i+1)%k==0)
{
printf("%d ",max);
max=0;
}
}
return 0;
}
C++ (CPP)
#include <bits/stdc++.h>
using namespace std;
int main(int argc, char** argv)
{
int n, k;
cin >> n;
vector<int> v(n);
for(int i = 0; i < n; i++)
cin >> v[i];
cin >> k;
for(int i = 0; i < n-(n%k); i += k)
cout << *max_element(v.begin()+i,v.begin()+i+k)<<" ";
}
JAVA
import java.util.Scanner;
import java.util.Collections;
import java.util.ArrayList;
public class Hello {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
sc.nextLine();
ArrayList<Integer> arr = new ArrayList<Integer>();
for(int i=0;i<n;i++){
arr.add(sc.nextInt());
}
sc.nextLine();
int k = sc.nextInt();
for(int i=0;i<(n-k+1);i+=k){
System.out.print(Collections.max(arr.subList(i,i+k))+" ");
}
}
}
PYTHON
n=int(input())
l=list(map(int,input().split()))
k=int(input())
for i in range(0,n-k+1,k):
print(max(l[i:i+k]),end=' ')

Comments
Post a Comment