C++程序中左侧和右侧下一个较大数的索引最大乘积
在这个问题中,我们给定一个数组arr[]。我们的任务是创建一个程序来计算左侧和右侧下一个较大数的索引的最大乘积。
问题描述 −
对于给定的数组,我们需要找到left[i]*right[i] 的最大值乘积。这两个数组定义如下:
left[i] = j, such that arr[i] <’. ‘ arr[j] and i > j. right[i] = j, such that arr[i] < arr[j] and i < j. *The array is 1 indexed.
让我们来看一个例子来理解这个问题,
输入
arr[6] = {5, 2, 3, 1, 8, 6}输出
15
解释
Creating left array,
left[] = {0, 1, 1, 3, 0, 5}
right[] = {5, 3, 5, 5, 0, 0}
Index products :
1 −> 0*5 = 0
2 −> 1*3 = 3
3 −> 1*5 = 5
4 −> 3*5 = 15
5 −> 0*0 = 0
6 −> 0*5 = 0最大乘积
15
解决方案 −
为了找到左侧和右侧较大元素索引的最大乘积,我们将首先找到左侧和右侧较大元素的索引,并将它们的乘积存储起来以进行比较。
现在,为了找到左侧和右侧最大的元素,我们将逐一检查左侧和右侧索引中大于给定元素的元素。为了查找,我们将使用栈,并执行以下操作:
If stack is empty −> push current index, tos = 1. Tos is top of the stack Else if arr[i] > arr[tos] −> tos = 1.
使用此方法,我们可以找到数组左侧和右侧所有大于给定元素的元素的索引值。
示例
程序说明了解决方案的工作原理:
#include <bits/stdc++.h>
using namespace std;
int* findNextGreaterIndex(int a[], int n, char ch ) {
int* greaterIndex = new int [n];
stack<int> index;
if(ch == 'R'){
for (int i = 0; i < n; ++i) {
while (!index.empty() && a[i] > a[index.top() − 1]) {
int indexVal = index.top();
index.pop();
greaterIndex[indexVal − 1] = i + 1;
}
index.push(i + 1);
}
}
else if(ch == 'L'){
for (int i = n − 1; i >= 0; i−−) {
while (!index.empty() && a[i] > a[index.top() − 1]) {
int indexVal = index.top();
index.pop();
greaterIndex[indexVal − 1] = i + 1;
}
index.push(i + 1);
}
}
return greaterIndex;
}
int calcMaxGreaterIndedxProd(int arr[], int n) {
int* left = findNextGreaterIndex(arr, n, 'L');
int* right = findNextGreaterIndex(arr, n, 'R');
int maxProd = −1000;
int prod;
for (int i = 1; i < n; i++) {
prod = left[i]*right[i];
if(prod > maxProd)
maxProd = prod;
}
return maxProd;
}
int main() {
int arr[] = { 5, 2, 3, 1, 8, 6};
int n = sizeof(arr) / sizeof(arr[1]);
cout<<"The maximum product of indexes of next greater on left and
right is "<<calcMaxGreaterIndedxProd(arr, n);
return 0;
}输出
The maximum product of indexes of next greater on left and right is 15
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP