1,725 views

2 Answers

0 votes
0 votes
Okay fine u can use dynamic programming here

here is the code

int arr[k+1];

for(int i=0;i<=k;i++)

arr[i]=0;

int inp[n+1];

for(int i=0;i<n;i++){

cin>>inp[i];

arr[inp[i]]++;

}

for(int i=1;i<=k;i++){

arr[i]+=arr[i-1];

}

// let q be the queries;

cin>>q;

while(q--){

int a , b;

cin>>a>>b;

cout<<arr[b]-arr[a-1]<<"\n";

}
0 votes
0 votes
Use counting sort.

We know that in counting sort we maintain the sum of the occurrences of all the elements in the array.

So array[b]-array[a-1] will return the answer in O(1) time.

Related questions

383
views
0 answers
0 votes
akash.dinkar12 asked Jun 28, 2019
383 views
Suppose that we were to rewrite the for loop header in line $10$ of the COUNTINGSORT as 10 for j = 1 to A.lengthShow that the algorithm still works properly. Is the modified algorithm stable?
404
views
1 answers
0 votes
akash.dinkar12 asked Jun 28, 2019
404 views
Prove that COUNTING-SORT is stable.
375
views
0 answers
0 votes
akash.dinkar12 asked Jun 28, 2019
375 views
COUNTING-SORT(A, B, k) 1 let C[0, ,k] be a new array 2 for i = 0 to k 3 C[i] = 0 4 for j = 1 to A.length 5 C[A[j]] = C[A[j]] + 1 6 // C ... - 1illustrate the operation of COUNTING-SORT on the array $A=\langle 6,0,2,0,1,3,4,6,1,3,2 \rangle $
736
views
1 answers
1 votes
akash.dinkar12 asked Jun 28, 2019
736 views
Explain why the worst-case running time for bucket sort is $\Theta(n^2)$. What simple change to the algorithm preserves its linear average-case running time and makes its worst-case running time $O(n\ lg\ n)$?