Prefix Minimum Query
Practice
4.8 (8 votes)
Introduction to dynamic programming 1
Algorithms
Dynamic programming
Problem
62% Success 1097 Attempts 50 Points 1.5s Time Limit 256MB Memory 1024 KB Max Code
You are given an array \(A\) having \(N\) integers. You have to answer \(Q\) queries. The \(i^{th}\) query is denoted by two integers \(L_i, R_i\). The answer to the \(i^{th}\) query is \(A_{L_i} + \min(A_{L_i},A_{L_i + 1}) + \dots + \min(A_{L_i},A_{L_i + 1} \dots, A_{R_i}) \).
For each query find the answer.
Note: Since the size of the input and output is large, please use in memory stack size accordingly otherwise you may see error.
Input format
- The first line of input contains two integers \(N, Q\) denoting the length of the array \(A\) and the number of queries respectively.
- The second line contains \(N\) integers \(A_1, A_2,\dots, A_N\) denoting elements of the array \(A\).
- Each of the next \(Q\) contains two space-separated integers \(L_i, R_i\).
Output format
For each query, print the answer in a separate line.
Constraints
\(1 \leq N, Q \leq 3\cdot 10^5\)
\(1\le A_i\le 10^9\)
\(1 \le L_i \le R_i \le N\)
Explanation
- The answer to the first query is \(= 3 + \min(3,7) + \min(3,7,2) = 3 + 3 + 2 = 8.\)
- The answer to the second query is \(= 7 + \min(7,2) + \min(7,2,1)+ \min(7,2,1,4) =7+2+1+1=11.\)
- The answer to the third query is \(= 5 + \min(5,3) + \min(5,3,7) = 5+3+3 = 11.\)
Code Editor
Please login to use the editor
You need to be logged in to access the code editor
Loading...
Please wait while we load the editor
Results
Custom Input
Run your code to see the output
Submissions
Please login to view your submissions
Similar Problems
Points:50
1 votes
Tags:
Dynamic ProgrammingIntroduction to Dynamic Programming 1Algorithms
Points:50
3 votes
Tags:
AlgorithmsApprovedDynamic ProgrammingHardReadyRecruitTwo pointer
Points:50
5 votes
Tags:
AlgorithmsApprovedDynamic ProgrammingGrammar-VerifiedHardHiringRecruit
Editorial
Login to unlock the editorial
Please login to use the editor
You need to be logged in to access the code editor
Loading...
Please wait while we load the editor
Results
Custom Input
Run your code to see the output