이 문제에서는 배열 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