![]() |
VOOZH | about |
You are given an array arr[] of positive integers. Your task is to process q queries, each consisting of three integers, of the following two types:
[1, L, R]: Find the maximum product of any two distinct elements in the subarray arr[L…R] (inclusive).[2, i, val]: Update the element at index i to val (i.e., set arr[i] = val) where val > 0Examples:
Input: n = 5, q = 3
arr[] = [1, 3, 4, 2, 5]
queries[][] = [ [1, 0, 2], [2, 1, 6], [1, 0, 2] ]
Output: 12 24
Explanation: For the query 1, the maximum product in a range [0, 2] is 3 * 4 = 12.
For the query 2, after an update, the array becomes [1, 6, 4, 2, 5]
For the query 3, the maximum product in a range [0, 2] is 6 * 4 = 24.
Table of Content
The idea is to examine every possible pair of elements in the range
[L, R], compute the product for each pair, and keep track of the maximum product found. By brute‑forcing all combinations, we guarantee that the highest possible product pair is identified.
Follow the below given steps:
maxProduct to a very small value and prepare variables to hold the indices or values of the best pair.i from L to R.j from i + 1 to R.currentProduct = arr[i] * arr[j].currentProduct exceeds maxProduct, update maxProduct and record the corresponding pair (arr[i], arr[j]).maxProduct.Below is given the implementation:
12 24
The idea is to use a segment tree where each node stores the largest and second largest elements within its corresponding segment. When a range query is performed, the maximum product is calculated by multiplying the two largest elements within that range. This approach ensures efficient query and update operations in logarithmic time.
Follow the below given steps:
[L, R], traverse the segment tree and merge results from overlapping segments, selecting the two largest elements.Below is given the implementation:
12 24