Answer to Question #229127 in C++ for Asjad

Question #229127

Harry loves numbers in the range [m1, m2] (m1 and m2 included). carry decides to gift harry an array of numbers for his birthday. harry wants to find the number of pairs of indices [l, r] for which the sum of all the elements in the range [l, r] lies between m1 and m2.


Come up with an algorithm with a worst case complexity of O(N2).

Now improvise this algorithm, assuming all numbers are positive integers.

What if the numbers could be negative as well? Can you think of an O(nlogn) solution in this case? (Hint: use sorting)


1
Expert's answer
2021-08-24T16:44:32-0400
// corecudr
#include <iostream>

using namespace std;

int n, m1, m2, gift[100], ans = 0;

int main()
{
    cin >> n >> m1 >> m2;
    for (int i = 0; i < n; i++) cin >> gift[i];
    for (int i = 0; i < n; i++) {
        for (int j = i; j < n; j++) {
            if (i != j && gift[i]+gift[j]<=m2 && gift[i]+gift[j]>=m1) ans++;
        }
    }
    cout << ans;

    return 0;
}
Sample Input 1:
5
7 15
2 3 5 10 9
Sample Output 1:
8

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS