📜  大小为 3 的双音子序列的最大乘积

📅  最后修改于: 2021-09-07 02:08:31             🧑  作者: Mango

给定一个大小为N的正整数数组arr[] ,任务是找到大小为 3 的双调子序列的最大乘积。
双调子序列:其中元素首先按升序,然后按降序排列的子序列。子序列中的元素遵循以下顺序 arr[i] < arr[j] > arr[k] for i < j < k 其中 i, j, k 是给定数组的索引。
注意:如果没有找到这样的元素,则打印 -1。

例子:

朴素的方法:一个简单的解决方案是找到大小为 3 的所有双音子序列的乘积,并在其中取最大值。

算法:

  • ans初始化为 -1,这样如果没有这样的子序列,则输出将为 -1。
  • 使用三个嵌套循环迭代数组,循环变量为 i、j 和 k,以选择数组的三个元素。
  • 检查 arr[j] > arr[i] 和 arr[j] > arr[k] 然后用ansarr[i] * arr[j] * arr[k]之间的最大值更新ans

下面是上述方法的实现:

C++
// C++ implementation to find the
// maximum product of the bitonic
// subsequence of size 3
 
#include 
using namespace std;
 
// Function to find the maximum
// product of bitonic subsequence
// of size 3
int maxProduct(int arr[], int n){
     
    // Initialize ans to -1 if no such
    // subsequence exist in the array
    int ans = -1;
     
    // Nested loops to choose the three
    // elements of the array
    for (int i = 0; i < n - 2; i++) {
        for (int j = i + 1; j < n - 1; j++) {
            for (int k = j + 1; k < n; k++) {
                 
                // Condition to check if
                // they form a bitonic subsequence
                if (arr[i] < arr[j] &&
                      arr[j] > arr[k])
                    ans = max(
                       ans, arr[i] * arr[j] * arr[k]
                       );
            }
        }
    }
    return ans;
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 8, 3, 7 };
 
    int n = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
    cout << maxProduct(arr, n) << endl;   
}


Java
// Java implementation to find the
// maximum product of the bitonic
// subsequence of size 3
import java.util.*;
 
class GFG{
  
// Function to find the maximum
// product of bitonic subsequence
// of size 3
static int maxProduct(int arr[], int n){
      
    // Initialize ans to -1 if no such
    // subsequence exist in the array
    int ans = -1;
      
    // Nested loops to choose the three
    // elements of the array
    for (int i = 0; i < n - 2; i++) {
        for (int j = i + 1; j < n - 1; j++) {
            for (int k = j + 1; k < n; k++) {
                  
                // Condition to check if
                // they form a bitonic subsequence
                if (arr[i] < arr[j] &&
                      arr[j] > arr[k])
                    ans = Math.max(
                       ans, arr[i] * arr[j] * arr[k]
                       );
            }
        }
    }
    return ans;
}
  
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 1, 8, 3, 7 };
  
    int n = arr.length;
  
    // Function call
    System.out.print(maxProduct(arr, n) +"\n");   
}
}
 
// This code is contributed by 29AjayKumar


Python3
# Python3 implementation to find the
# maximum product of the bitonic
# subsequence of size 3
 
# Function to find the maximum
# product of bitonic subsequence
# of size 3
def maxProduct(arr, n):
 
    # Initialize ans to -1 if no such
    # subsequence exist in the array
    ans = -1
 
    # Nested loops to choose the three
    # elements of the array
    for i in range(n - 2):
        for j in range(i + 1, n - 1):
            for k in range(j + 1, n):
 
                # Condition to check if
                # they form a bitonic subsequence
                if (arr[i] < arr[j] and arr[j] > arr[k]):
                    ans = max(ans, arr[i] * arr[j] * arr[k])
 
    return ans
 
# Driver Code
if __name__ == '__main__':
    arr= [ 1, 8, 3, 7]
 
    n = len(arr)
 
    # Function call
    print(maxProduct(arr, n))
 
# This code is contributed by mohit kumar 29


C#
// C# implementation to find the
// maximum product of the bitonic
// subsequence of size 3
using System;
 
class GFG {
 
     // Function to find the maximum
     // product of bitonic subsequence
    // of size 3
    static int maxProduct(int[] arr, int n)
    {
        // Initialize ans to -1 if no such
        // subsequence exist in the array
        int ans = -1;
          
        // Nested loops to choose the three
        // elements of the array
        for (int i = 0; i < n - 2; i++) {
            for (int j = i + 1; j < n - 1; j++) {
                for (int k = j + 1; k < n; k++) {
                      
                    // Condition to check if
                    // they form a bitonic subsequence
                    if (arr[i] < arr[j] &&
                          arr[j] > arr[k])
                        ans = Math.Max(ans, arr[i] * arr[j] * arr[k]
                           );
                }
            }
        }
        return ans;
    }
     
    // Driver code
    static void Main()
    {
        int[] arr = new int[] { 1, 8, 3, 7 };
        int n = arr.Length;
     
        // Function call to find product
        Console.Write(maxProduct(arr, n));
    }
}
 
// This code is contributed by shubhamsingh


Javascript


C++
// C++ implementation to find the
// maximum product of the bitonic
// subsequence of size 3
 
#include 
using namespace std;
 
// Function to find the maximum
// product of bitonic subsequence
// of size 3
int maxProduct(int arr[], int n){
     
    // Self Balancing BST
    set s;
    set::iterator it;
     
    // Left array to store the
    // maximum smallest value for
    // every element in left of it
    int Left[n];
 
    // Right array to store the
    // maximum smallest value for
    // every element in right of it
    int Right[n];
 
    // Loop to find the maximum
    // smallest element in left of
    // every element in array
    for (int i = 0; i < n; i++) {
        s.insert(arr[i]);
        it = s.lower_bound(arr[i]);
         
        // Condition to check if there
        // is a maximum smallest element
        if (it != s.begin()) {
            it--;
            Left[i] = *it;
        }
        else {
            Left[i] = -1;
        }
    }
    // Clear Set
    s.clear();
     
    // Loop to find the maximum
    // smallest element in right of
    // every element in array
    for (int i = n - 1; i >= 0; i--) {
        s.insert(arr[i]);
        it = s.lower_bound(arr[i]);
         
        // Condition to check if there
        // is such element exists
        if (it != s.begin()) {
            it--;
            Right[i] = *it;
        }
         
        // If no such element exists.
        else {
            Right[i] = -1;
        }
    }
    int ans = -1;
     
    // Loop to find the maximum product
    // bitonic subsequence of size 3
    for (int i = 0; i < n; i++) {
        if (Left[i] > 0 and Right[i] > 0)
            ans = max(ans, arr[i] * Left[i] * Right[i]);
    }
 
    if (ans < 0) {
        return -1;
    }
    else {
        return ans;
    }
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 8, 3, 7, 5, 6, 7 };
    int n = sizeof(arr) / sizeof(arr[0]);
     
    // Function Call
    cout << maxProduct(arr, n);
}


Java
// Java implementation to find the
// maximum product of the bitonic
// subsequence of size 3
import java.util.*;
import java.lang.System;
 
class GFG{
 
 public static int maxProduct(int arr[],int n)
 {
    // Self Balancing BST
    TreeSet ts = new TreeSet();
 
    // Left array to store the
    // maximum smallest value for
    // every element in left of it
    int Left[] = new int[n];
  
    // Right array to store the
    // maximum smallest value for
    // every element in right of it
    int Right[] = new int[n];
 
    // Loop to find the maximum
    // smallest element in left of
    // every element in array
    for(int i = 0; i < n; i++)
    {
        ts.add(arr[i]);
 
        if(ts.lower(arr[i]) == null)
            Left[i] = -1;
        else
            Left[i] = ts.lower(arr[i]);
    }
 
    ts.clear();
 
    // Loop to find the maximum
    // smallest element in right of
    // every element in array
    for (int i = n-1; i >= 0; i--)
    {
        ts.add(arr[i]);
 
        if(ts.lower(arr[i]) == null)
            Right[i] = -1;
        else
            Right[i] = ts.lower(arr[i]);
    }
 
    // Loop to find the maximum product
    // bitonic subsequence of size 3
    int ans = 0;
 
    for(int i = 0; i < n; i++)
    {
        //Condition to check whether a sequence is bitonic or not
        if(Left[i] != -1 && Right[i] != -1)
            ans = Math.max(ans, Left[i] * arr[i] * Right[i]);
    }
 
    return ans;
 }
 
 // Driver Code
 public static void main(String args[])
{
    int arr[] = {1, 8, 3, 7, 5, 6, 7 };
 
    int n = arr.length;
 
    int maximum_product = maxProduct(arr,n);
 
    System.out.println(maximum_product);
}
}
 
// This code is contributed by Siddhi.


输出:
56

性能分析:

  • 时间复杂度:与上述方法一样,有三个嵌套循环来查找大小为 3 的双音子序列的最大乘积,因此时间复杂度将为O(N 3 )
  • 辅助空间:与上述方法一样,没有使用额外的空间,因此辅助空间将为O(1)

有效的方法:想法是在每个索引的左侧和右侧找到最大值,这些值小于当前索引中存在的元素,为此使用自平衡 BST,然后为每个元素找到最大乘积可以形成并最大限度地利用这些产品。
自平衡 BST 在 C++ 中实现,在Java实现 TreeSet。

算法:

  • 声明一个自平衡 BST(比如s )。
  • 声明两个新数组left[]right[]以将 arr[i] 的下限存储在 left[i] 中该元素的左侧,并将 arr[i] 的下限存储在 right[i] 中该元素的右侧。
  • 运行一个从 0 到 length – 1 的循环以找到该元素左侧的 arr[i] 的下限并将其存储在 left[i] 中。
  • 运行一个长度从 -1 到 0 的循环,以在该元素的右侧找到 arr[i] 的下限并将其存储在 right[i] 中。
  • 运行从 0 到 length – 1 的循环,以找到可以使用该元素形成的双音子序列,从而使用 left[] 和 right[] 数组获得最大乘积。也就是说,对于每个元素,可以形成的最大乘积双音子序列是left[i] * right[i] * arr[i]

下面是上述方法的实现:

C++

// C++ implementation to find the
// maximum product of the bitonic
// subsequence of size 3
 
#include 
using namespace std;
 
// Function to find the maximum
// product of bitonic subsequence
// of size 3
int maxProduct(int arr[], int n){
     
    // Self Balancing BST
    set s;
    set::iterator it;
     
    // Left array to store the
    // maximum smallest value for
    // every element in left of it
    int Left[n];
 
    // Right array to store the
    // maximum smallest value for
    // every element in right of it
    int Right[n];
 
    // Loop to find the maximum
    // smallest element in left of
    // every element in array
    for (int i = 0; i < n; i++) {
        s.insert(arr[i]);
        it = s.lower_bound(arr[i]);
         
        // Condition to check if there
        // is a maximum smallest element
        if (it != s.begin()) {
            it--;
            Left[i] = *it;
        }
        else {
            Left[i] = -1;
        }
    }
    // Clear Set
    s.clear();
     
    // Loop to find the maximum
    // smallest element in right of
    // every element in array
    for (int i = n - 1; i >= 0; i--) {
        s.insert(arr[i]);
        it = s.lower_bound(arr[i]);
         
        // Condition to check if there
        // is such element exists
        if (it != s.begin()) {
            it--;
            Right[i] = *it;
        }
         
        // If no such element exists.
        else {
            Right[i] = -1;
        }
    }
    int ans = -1;
     
    // Loop to find the maximum product
    // bitonic subsequence of size 3
    for (int i = 0; i < n; i++) {
        if (Left[i] > 0 and Right[i] > 0)
            ans = max(ans, arr[i] * Left[i] * Right[i]);
    }
 
    if (ans < 0) {
        return -1;
    }
    else {
        return ans;
    }
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 8, 3, 7, 5, 6, 7 };
    int n = sizeof(arr) / sizeof(arr[0]);
     
    // Function Call
    cout << maxProduct(arr, n);
}

Java

// Java implementation to find the
// maximum product of the bitonic
// subsequence of size 3
import java.util.*;
import java.lang.System;
 
class GFG{
 
 public static int maxProduct(int arr[],int n)
 {
    // Self Balancing BST
    TreeSet ts = new TreeSet();
 
    // Left array to store the
    // maximum smallest value for
    // every element in left of it
    int Left[] = new int[n];
  
    // Right array to store the
    // maximum smallest value for
    // every element in right of it
    int Right[] = new int[n];
 
    // Loop to find the maximum
    // smallest element in left of
    // every element in array
    for(int i = 0; i < n; i++)
    {
        ts.add(arr[i]);
 
        if(ts.lower(arr[i]) == null)
            Left[i] = -1;
        else
            Left[i] = ts.lower(arr[i]);
    }
 
    ts.clear();
 
    // Loop to find the maximum
    // smallest element in right of
    // every element in array
    for (int i = n-1; i >= 0; i--)
    {
        ts.add(arr[i]);
 
        if(ts.lower(arr[i]) == null)
            Right[i] = -1;
        else
            Right[i] = ts.lower(arr[i]);
    }
 
    // Loop to find the maximum product
    // bitonic subsequence of size 3
    int ans = 0;
 
    for(int i = 0; i < n; i++)
    {
        //Condition to check whether a sequence is bitonic or not
        if(Left[i] != -1 && Right[i] != -1)
            ans = Math.max(ans, Left[i] * arr[i] * Right[i]);
    }
 
    return ans;
 }
 
 // Driver Code
 public static void main(String args[])
{
    int arr[] = {1, 8, 3, 7, 5, 6, 7 };
 
    int n = arr.length;
 
    int maximum_product = maxProduct(arr,n);
 
    System.out.println(maximum_product);
}
}
 
// This code is contributed by Siddhi.
输出:
126

性能分析:

  • 时间复杂度: O(NlogN)。
  • 辅助空间: O(N)。

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live