Given an array arr[] and an integer K, the task is to calculate the ratio of all subarrays of size K.
Examples:
Input: arr[] = {24, 3, 2, 1}, K = 3
Output: 4 1.5
Explanation:
All subarrays of size K and their ratio:
Subarray 1: {24, 3, 2} = 24 / 3 / 2 = 4
Subarray 2: {3, 2, 1} = 3 / 2 / 1= 1.5
Input: arr[] = {1, -2, 3, -4, 5, 6}, K = 2
Output: -0.5 -0.666667 -0.75 -0.8 0.833333
Approach: The idea is to iterate over every subarray of size K present in the given array and follow the steps below to solve the problem:
- Initialize a variable, say ratio with the first element of the subarray.
- Iterate over the remaining subarray and keep on dividing ratio by the encountered elements one by one.
- Finally, print the final value of ratio for that subarray.
- Repeat the above steps for all subarrays.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int calcRatio( double arr[], int n, int k)
{
for ( int i = 0; i <= n - k; i++) {
double ratio = arr[i];
for ( int j = i + 1; j < k + i; j++)
ratio /= arr[j];
cout << ratio << " " ;
}
}
int main()
{
double arr[] = { 24, 3, 2, 1 };
int n = sizeof (arr) / sizeof (arr[0]);
int k = 3;
calcRatio(arr, n, k);
return 0;
}
|
Java
import java.util.*;
class GFG{
static void calcRatio( double arr[], int n,
int k)
{
for ( int i = 0 ; i <= n - k; i++)
{
double ratio = arr[i];
for ( int j = i + 1 ; j < k + i; j++)
ratio /= arr[j];
System.out.print(ratio + " " );
}
}
public static void main (String[] args)
{
double arr[] = { 24 , 3 , 2 , 1 };
int n = arr.length;
int k = 3 ;
calcRatio(arr, n, k);
}
}
|
Python3
def calcRatio(arr, n, k):
for i in range (n - k + 1 ):
ratio = arr[i]
for j in range (i + 1 , k + i):
ratio = ratio / arr[j]
print (ratio, end = " " )
arr = [ 24 , 3 , 2 , 1 ]
n = len (arr)
k = 3
calcRatio(arr, n, k)
|
C#
using System;
class GFG{
static void calcRatio( double []arr, int n,
int k)
{
for ( int i = 0; i <= n - k; i++)
{
double ratio = arr[i];
for ( int j = i + 1; j < k + i; j++)
ratio /= arr[j];
Console.Write(ratio + " " );
}
}
public static void Main( string [] args)
{
double []arr = { 24, 3, 2, 1 };
int n = arr.Length;
int k = 3;
calcRatio(arr, n, k);
}
}
|
Javascript
<script>
function calcRatio(arr, n, k)
{
for ( var i = 0; i <= n - k; i++) {
var ratio = arr[i];
for ( var j = i + 1; j < k + i; j++)
ratio /= arr[j];
document.write(ratio + " " );
}
}
var arr = [ 24, 3, 2, 1 ];
var n = arr.length;
var k = 3;
calcRatio(arr, n, k);
</script>
|
Time Complexity: O(N2)
Auxiliary Space: O(1)