a) Given an array and an integer K, find the maximum for each and every contiguous subarray of size k.
Examples :
Input: arr[] = {1, 2, 3, 1, 4, 5, 2, 3, 6}, K = 3
Output: 3 3 4 5 5 5 6
Explanation:
Maximum of 1, 2, 3 is 3
Maximum of 2, 3, 1 is 3
Maximum of 3, 1, 4 is 4
Maximum of 1, 4, 5 is 5
Maximum of 4, 5, 2 is 5
Maximum of 5, 2, 3 is 5
Maximum of 2, 3, 6 is 6
Input: arr[] = {8, 5, 10, 7, 9, 4, 15, 12, 90, 13}, K = 4
Output: 10 10 10 15 15 90 90
Explanation:
Maximum of first 4 elements is 10, similarly for next 4
elements (i.e from index 1 to 4) is 10, So the sequence
generated is 10 10 10 15 15 90 90
Recommended: Please solve it on “PRACTICE” first, before moving on to the solution.
Method 1: This is a simple method to solve the above problem.
Approach:
The idea is very basic run a nested loop, the outer loop which will mark the starting point of the subarray of length k, the inner loop will run from the starting index to index+k, k elements from starting index and print the maximum element among these k elements.
Algorithm:
Create a nested loop, the outer loop from starting index to n – k th elements. The inner loop will run for k iterations.
Create a variable to store the maximum of k elements traversed by the inner loop.
Find the maximum of k elements traversed by the inner loop.
Print the maximum element in every iteration of outer loop
b) How to Find the Sum of First 25 Even Numbers?
The below workout with step by step calculation shows how to find what is the sum of first 25 even numbers by applying arithmetic progression. It's one of the easiest methods to quickly find the sum of given number series.
step 1
Address the formula, input parameters & values.
Input parameters & values:
The number series 2, 4, 6, 8, 10, 12, . . . . , 50.
The first term a = 2
The common difference d = 2
Total number of terms n = 25
step 2
apply the input parameter values in the AP formula
Sum = n/2 x (a + Tn)
= 25/2 x (2 + 50)
= (25 x 52)/ 2
= 1300/2
2 + 4 + 6 + 8 + 10 + 12 + . . . . + 50 = 650
Therefore, 650 is the sum of first 25 even numbers.
c) The odd numbers are: 1, 3, 5, 7, 9,….49
The first term is = 1
The common difference is, d = 2
The total no.of terms is, n = 25
Sum = n/2 x (a+Tn)
=25/2 x (1+49)
=1250/2
= 625
Therefore, the sum of first 25 odd numbers is 625.