给定一个大小为N的数组arr[] ,任务是通过执行以下操作来打印给定数组可以缩小到的最小可能大小:
- 删除任何两个相邻的元素,比如arr[i]和arr[i+1]并在数组中的那个位置插入一个元素arr[i] * arr[i+1] 。
- 如果所有数组元素变得相等,则打印数组的大小。
例子:
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
方法:该方法基于这样一种思想,即如果所有数组元素都相同,则无法对给定数组执行给定的操作。否则,在任何情况下,数组大小都可以减少到 1。以下是步骤:
- 迭代给定的数组arr[] 。
- 如果数组的所有元素都相同,则打印N作为所需答案。
- 否则,始终选择提供最大乘积的相邻元素以将arr[]的大小减少到 1。因此,最小可能的大小将是1 。
下面是上述方法的实现:
C++
// C++ implementation of the above approach
#include
using namespace std;
// Function to minimize the size of
// array by performing given operations
int minLength(int arr[], int N)
{
for (int i = 1; i < N; i++) {
// If all array elements
// are not same
if (arr[0] != arr[i]) {
return 1;
}
}
// If all array elements
// are same
return N;
}
// Driver Code
int main()
{
int arr[] = { 2, 1, 3, 1 };
int N = sizeof(arr) / sizeof(arr[0]);
// Function Call
cout << minLength(arr, N);
return 0;
}
Java
// Java implementation of the above approach
import java.io.*;
class GFG{
// Function to minimize the size of
// array by performing given operations
static int minLength(int arr[], int N)
{
for(int i = 1; i < N; i++)
{
// If all array elements
// are not same
if (arr[0] != arr[i])
{
return 1;
}
}
// If all array elements
// are same
return N;
}
// Driver Code
public static void main(String[] args)
{
int[] arr = { 2, 1, 3, 1 };
int N = arr.length;
// Function call
System.out.print(minLength(arr, N));
}
}
// This code is contributed by akhilsaini
Python3
# Python3 implementation of the above approach
# Function to minimize the size of
# array by performing given operations
def minLength(arr, N):
for i in range(1, N):
# If all array elements
# are not same
if (arr[0] != arr[i]):
return 1
# If all array elements
# are same
return N
# Driver Code
if __name__ == "__main__":
arr = [ 2, 1, 3, 1 ]
N = len(arr)
# Function call
print(minLength(arr, N))
# This code is contributed by akhilsaini
C#
// C# implementation of the above approach
using System;
class GFG{
// Function to minimize the size of
// array by performing given operations
static int minLength(int[] arr, int N)
{
for(int i = 1; i < N; i++)
{
// If all array elements
// are not same
if (arr[0] != arr[i])
{
return 1;
}
}
// If all array elements
// are same
return N;
}
// Driver Code
public static void Main()
{
int[] arr = { 2, 1, 3, 1 };
int N = arr.Length;
// Function call
Console.Write(minLength(arr, N));
}
}
// This code is contributed by akhilsaini
Javascript
1
时间复杂度: O(N)
辅助空间: O(1)
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live