C++ 程序中递增子序列的最大乘积
在这个问题中,我们得到了一个长度为 n 的数组 arr[]。我们的任务是找到递增子序列的最大乘积。
问题描述 − 我们需要从数组元素中找到任意大小的递增子序列的最大乘积。
让我们举个例子来理解这个问题,
输入
arr[] = {5, 4, 6, 8, 7, 9}
输出
2160
说明
All Increasing subsequence: {5,6,8,9}. Prod = 2160 {5,6,7,9}. Prod = 1890 Here, we have considered only max size subsequence.
解决方法
解决这个问题的一个简单方法是使用动态规划的方法。为此,我们将存储到给定数组元素为止的最大乘积的递增子序列,然后存储在一个数组中。
算法
初始化 −
prod[] with elements of arr[]. maxProd = −1000
步骤 1 −
Loop for i −> 0 to n−1
步骤 1.1 −
Loop for i −> 0 to i
步骤 1.1.1
Check if the current element creates an increasing subsequence i.e. arr[i]>arr[j] and arr[i]*prod[j]> prod[i] −> prod[i] = prod[j]*arr[i]
步骤 2 −
find the maximum element of the array. Following steps 3 and 4.
步骤 3 −
Loop form i −> 0 to n−1
步骤 4 −
if(prod[i] > maxProd) −> maxPord = prod[i]
步骤 5 −
return maxProd.
示例
程序展示了我们解决方案的实现,
#include <iostream> using namespace std; long calcMaxProdSubSeq(long arr[], int n) { long maxProdSubSeq[n]; for (int i = 0; i < n; i++) maxProdSubSeq[i] = arr[i]; for (int i = 1; i < n; i++) for (int j = 0; j < i; j++) if (arr[i] > arr[j] && maxProdSubSeq[i] < (maxProdSubSeq[j] * arr[i])) maxProdSubSeq[i] = maxProdSubSeq[j] * arr[i]; long maxProd = −1000 ; for(int i = 0; i < n; i++){ if(maxProd < maxProdSubSeq[i]) maxProd = maxProdSubSeq[i]; } return maxProd; } int main() { long arr[] = {5, 4, 6, 8, 7, 9}; int n = sizeof(arr) / sizeof(arr[0]); cout<<"The maximum product of an increasing subsequence is "<<calcMaxProdSubSeq(arr, n); return 0; }
输出
The maximum product of an increasing subsequence is 2160
广告