Prefix Minimum Query

4.8

8 votes
Introduction to Dynamic Programming 1, Algorithms, Dynamic Programming
Problem

You are given an array A having N integers. You have to answer Q queries. The ith query is denoted by two integers Li,Ri. The answer to the ith query is ALi+min(ALi,ALi+1)++min(ALi,ALi+1,ARi).

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 A1,A2,,AN denoting elements of the array A.
  • Each of the next Q contains two space-separated integers Li,Ri.

Output format

For each query, print the answer in a separate line.

Constraints

1N,Q31051Ai1091LiRiN

 

Time Limit: 1.5
Memory Limit: 256
Source Limit:
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.
Editor Image

?