Smallest array that can be obtained by replacing adjacent pairs with their products
Last Updated :
05 May, 2021
Given an array arr[] of size N, the task is to print the least possible size the given array can be reduced to by performing the following operations:
- Remove any two adjacent elements, say arr[i] and arr[i+1] and insert a single element arr[i] * arr[i+1] at that position in the array.
- If all array elements become equal, then print the size of the array.
Examples:
Input: arr[] = {1, 7, 7, 1, 7, 1}
Output: 1
Explanation:
Pick arr[0] and arr[1] and replace with arr[0]*arr[1], arr[] = {7, 7, 1, 7, 1}
Pick arr[0] and arr[1] and replace with arr[0]*arr[1], arr[] = {49, 1, 7, 1}
Pick arr[0] and arr[1] and replace with arr[0]*arr[1], arr[] = {49, 7, 1}
Pick arr[0] and arr[1] and replace with arr[0]*arr[1], arr[] = {343, 1}
Pick arr[0] and arr[1] and replace with arr[0]*arr[1], arr[] = {343}
Input: arr[] = {2, 2, 2, 2}
Output: 4
Approach: The approach is based on the idea that if all array elements are the same, then the given operations can’t be performed on the given array. Otherwise, in every case, the array size can be reduced to 1. Below are the steps:
- Iterate over the given array arr[].
- If all elements of the array are same, then print N as the required answer.
- Otherwise, always pick adjacent elements which give the maximum product to reduce the size of arr[] to 1. Therefore, the minimum possible size will be 1.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int minLength( int arr[], int N)
{
for ( int i = 1; i < N; i++) {
if (arr[0] != arr[i]) {
return 1;
}
}
return N;
}
int main()
{
int arr[] = { 2, 1, 3, 1 };
int N = sizeof (arr) / sizeof (arr[0]);
cout << minLength(arr, N);
return 0;
}
|
Java
import java.io.*;
class GFG{
static int minLength( int arr[], int N)
{
for ( int i = 1 ; i < N; i++)
{
if (arr[ 0 ] != arr[i])
{
return 1 ;
}
}
return N;
}
public static void main(String[] args)
{
int [] arr = { 2 , 1 , 3 , 1 };
int N = arr.length;
System.out.print(minLength(arr, N));
}
}
|
Python3
def minLength(arr, N):
for i in range ( 1 , N):
if (arr[ 0 ] ! = arr[i]):
return 1
return N
if __name__ = = "__main__" :
arr = [ 2 , 1 , 3 , 1 ]
N = len (arr)
print (minLength(arr, N))
|
C#
using System;
class GFG{
static int minLength( int [] arr, int N)
{
for ( int i = 1; i < N; i++)
{
if (arr[0] != arr[i])
{
return 1;
}
}
return N;
}
public static void Main()
{
int [] arr = { 2, 1, 3, 1 };
int N = arr.Length;
Console.Write(minLength(arr, N));
}
}
|
Javascript
<script>
function minLength(arr, N)
{
for (let i = 1; i < N; i++)
{
if (arr[0] != arr[i])
{
return 1;
}
}
return N;
}
let arr = [ 2, 1, 3, 1 ];
let N = arr.length;
document.write(minLength(arr, N));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...