Computer Science, asked by annu5686, 1 year ago

Maximum sum query you are given an array a and q queries. Each query consists of 2 integers l and r. The answer to each query will be max(ai + ai+1 +.+ aj,l<=i<=j<=r).

Answers

Answered by tripathiakshita48
0

Answer:

Here is the code to calculate Maximum sum query

Explanation:

Determine the array's MAX value.

The instances of each element should be placed in an array of size MAX.

Since we want to provide the best response possible, we will begin iterating from the MAX value down to 0.

If the ith element occurs more often than zero, we include it to our response, reduce the occurrences of the i-1th element by 1, and also reduce the ith element's occurrence by 1 because we have included it.

Since we are already starting from the end and the i+1th element has already been handled, we don't need to reduce its frequency.

The ith element may appear more than once, so hold off on reducing it for the time being.

// CPP program to Maximize the sum of selected

// numbers by deleting three consecutive numbers.

#include <bits/stdc++.h>

using namespace std;

// function to maximize the sum of selected numbers

int maximizeSum(int arr[], int n)

{

// Largest element in the array

int mx = -1;

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

 mx = max(mx, arr[i]);

}

// An array to count the occurrence of each element

int freq[mx + 1];

memset(freq, 0, sizeof(freq));

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

 freq[arr[i]]++;

}

// ans to store the result

int ans = 0, i = mx;

// Using the above mentioned approach

while (i > 0) {

 // if occurrence is greater than 0

 if (freq[i] > 0) {

  // add it to ans

  ans += i;

  // decrease i-1th element by 1

  freq[i - 1]--;

  // decrease ith element by 1

  freq[i]--;

 }

 else {

  // decrease i

  i--;

 }

}

return ans;

}

// Driver code

int main()

{

int a[] = { 1, 2, 3 };

int n = sizeof(a) / sizeof(a[0]);

cout << maximizeSum(a, n);

return 0;

}

See more:

https://brainly.in/question/54427370

#SPJ1

Similar questions