📌  相关文章
📜  通过将相邻对替换为其乘积可获得的最小数组

📅  最后修改于: 2021-05-14 08:17:37             🧑  作者: Mango

给定大小为N的数组arr [] 任务是打印给定数组可以通过执行以下操作而减小到的最小大小:

  • 删除任意两个相邻的元素,例如arr [i]arr [i + 1],并在数组中的该位置插入单个元素arr [i] * arr [i + 1]
  • 如果所有数组元素都相等,则打印数组的大小。

例子:

方法:该方法基于以下想法:如果所有数组元素都相同,则无法在给定数组上执行给定的操作。否则,在每种情况下,都可以将数组大小减小为1。以下是步骤:

  1. 遍历给定数组arr []
  2. 如果数组的所有元素都相同,则将N打印为所需答案。
  3. 否则,请始终选择能够提供最大乘积以将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


输出:
1



时间复杂度: O(N)
辅助空间: O(1)