The Wayback Machine - https://web.archive.org/web/20240817124823/https://www.geeksforgeeks.org/maximum-cost-of-a-value-over-the-range-1-n-such-that-values-lies-in-at-most-k-given-ranges/
Open In App

Maximum cost of a value over the range [1, N] such that values lies in at most K given ranges

Last Updated : 14 Jul, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a positive integer N and an array arr[] of size M of the type {L, R, C} such that C is the cost of choosing an element in the range [L, R] and a positive integer K, the task is to find the maximum cost of a value over the range [1, N] such that values lies in at most K given range arr[].

Examples:

Input: arr[] = {{2, 8, 800}, {6, 9, 1500}, {4, 7, 200}, {3, 5, 400}}, K = 2
Output: 2300
Explanation:
The item chosen is 6 and the costs chosen are 0th and 1st indices such that the 6 belongs into the range of 2 to 8 and 6 to 9. Therefore the total sum of the costs 800 + 1500 is 2300, which is maximum.

Input: arr[] = {{1, 3, 400}, {5, 5, 500}, {2, 3, 300}}, K = 3
Output: 700

Approach: The given problem can be solved by storing all the costs for every item i which lies in the interval range L to R, and sorting the chosen costs in non-increasing order. Then comparing the sum of the first K costs of all items. Below steps can be followed:

  • Initialize a variable, say totMaxSum = 0 to store the maximum sum of the cost.
  • Initialize a variable, say sum = 0 to store the ith item sum of the cost.
  • Initialize a vector, say currCost to store the costs for the ith item.
  • Iterate over the range of [1, N] using the variable i and nested iterate over the range of [0, M – 1] using the variable j and perform the following steps:
    • If the value of i lies over the range [arr[i][0], arr[i][1]], then add the value of arr[i][2] to the vector currCost.
    • Sort the vector currCost in non-increasing order.
    • Iterate over the vector currCost and add the values of the first K elements to sum.
    • Update the value of totMaxSum by max(totMaxSum, sum).
  • After completing the above steps, print the value of totMaxSum as the maximum sum.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to maximize the total cost
// by choosing an item which lies in
// the interval L to R
void maxTotalCost(vector<vector<int> >& arr,
                  int M, int N, int K)
{
    // Stores the total maximum sum
    int totMaxSum = 0;
 
    for (int i = 1; i <= N; ++i) {
 
        // Stores the cost for ith item
        vector<int> currCost;
 
        for (int j = 0; j < M; ++j) {
 
            // Check if the ith item
            // belongs in the interval
            if (arr[j][0] <= i
                && arr[j][1] >= i) {
 
                // Add the jth cost
                currCost.push_back(arr[j][2]);
            }
        }
 
        // Sort the currCost[] in the
        // non increasing order
        sort(currCost.begin(),
             currCost.end(),
             greater<int>());
 
        // Stores the ith item sum
        int sum = 0;
 
        // Choose at most K costs
        for (int j = 0;
             j < K
             && j < currCost.size();
             ++j) {
 
            // Update the sum
            sum += currCost[j];
        }
 
        // Update the totMaxSum
        totMaxSum = max(totMaxSum, sum);
    }
 
    // Print the value of totMaxSum
    cout << totMaxSum << endl;
}
 
// Driver Code
int main()
{
    int N = 10;
    vector<vector<int> > arr = { { 2, 8, 800 },
                                 { 6, 9, 1500 },
                                 { 4, 7, 200 },
                                 { 3, 5, 400 } };
    int M = arr.size();
    int K = 2;
 
    maxTotalCost(arr, M, N, K);
 
    return 0;
}


Java




// Java program for the above approach
import java.util.*;
 
class GFG
{
 
// Function to maximize the total cost
// by choosing an item which lies in
// the interval L to R
static void maxTotalCost(int[][] arr,
                  int M, int N, int K)
{
   
    // Stores the total maximum sum
    int totMaxSum = 0;
 
    for (int i = 1; i <= N; ++i) {
 
        // Stores the cost for ith item
        Vector<Integer> currCost = new Vector<Integer>();
 
        for (int j = 0; j < M; ++j) {
 
            // Check if the ith item
            // belongs in the interval
            if (arr[j][0] <= i
                && arr[j][1] >= i) {
 
                // Add the jth cost
                currCost.add(arr[j][2]);
            }
        }
 
        // Sort the currCost[] in the
        // non increasing order
        Collections.sort(currCost,Collections.reverseOrder());
 
        // Stores the ith item sum
        int sum = 0;
 
        // Choose at most K costs
        for (int j = 0;
             j < K
             && j < currCost.size();
             ++j) {
 
            // Update the sum
            sum += currCost.get(j);
        }
 
        // Update the totMaxSum
        totMaxSum = Math.max(totMaxSum, sum);
    }
 
    // Print the value of totMaxSum
    System.out.print(totMaxSum +"\n");
}
 
// Driver Code
public static void main(String[] args)
{
    int N = 10;
    int[][]  arr = { { 2, 8, 800 },
                                 { 6, 9, 1500 },
                                 { 4, 7, 200 },
                                 { 3, 5, 400 } };
    int M = arr.length;
    int K = 2;
 
    maxTotalCost(arr, M, N, K);
}
}
 
// This code is contributed by shikhasingrajput


Python3




# python program for the above approach
 
# Function to maximize the total cost
# by choosing an item which lies in
# the interval L to R
def maxTotalCost(arr, M, N, K):
 
    # Stores the total maximum sum
    totMaxSum = 0
 
    for i in range(1, N + 1):
 
        # Stores the cost for ith item
        currCost = []
 
        for j in range(0, M):
 
            # Check if the ith item
            # belongs in the interval
            if (arr[j][0] <= i and arr[j][1] >= i):
 
                # Add the jth cost
                currCost.append(arr[j][2])
 
                # Sort the currCost[] in the
                # non increasing order
        currCost.sort()
 
        # Stores the ith item sum
        sum = 0
 
        # Choose at most K costs
        for j in range(0, K):
 
                        # Update the sum
            if j >= len(currCost):
                break
            sum += currCost[j]
 
            # Update the totMaxSum
        totMaxSum = max(totMaxSum, sum)
 
        # Print the value of totMaxSum
    print(totMaxSum)
 
# Driver Code
if __name__ == "__main__":
 
    N = 10
    arr = [[2, 8, 800],
           [6, 9, 1500],
           [4, 7, 200],
           [3, 5, 400]
           ]
    M = len(arr)
    K = 2
 
    maxTotalCost(arr, M, N, K)
 
    # This code is contributed by rakeshsahni


C#




// C++ program for the above approach
using System;
using System.Collections.Generic;
class GFG
{
   
    // Function to maximize the total cost
    // by choosing an item which lies in
    // the interval L to R
    static void maxTotalCost(int[, ] arr, int M, int N,
                             int K)
    {
        // Stores the total maximum sum
        int totMaxSum = 0;
 
        for (int i = 1; i <= N; ++i) {
 
            // Stores the cost for ith item
            List<int> currCost = new List<int>();
 
            for (int j = 0; j < M; ++j) {
 
                // Check if the ith item
                // belongs in the interval
                if (arr[j, 0] <= i && arr[j, 1] >= i) {
 
                    // Add the jth cost
                    currCost.Add(arr[j, 2]);
                }
            }
 
            // Sort the currCost[] in the
            // non increasing order
            currCost.Sort();
 
            // Stores the ith item sum
            int sum = 0;
 
            // Choose at most K costs
            for (int j = 0; j < K && j < currCost.Count;
                 ++j) {
 
                // Update the sum
                sum += currCost[j];
            }
 
            // Update the totMaxSum
            totMaxSum = Math.Max(totMaxSum, sum);
        }
 
        // Print the value of totMaxSum
        Console.WriteLine(totMaxSum);
    }
 
    // Driver Code
    public static void Main()
    {
        int N = 10;
        int[, ] arr = { { 2, 8, 800 },
                        { 6, 9, 1500 },
                        { 4, 7, 200 },
                        { 3, 5, 400 } };
        int M = arr.GetLength(0);
        int K = 2;
 
        maxTotalCost(arr, M, N, K);
    }
}
 
// This code is contributed by ukasp.


Javascript




<script>
        // JavaScript Program to implement
        // the above approach
 
        // Function to maximize the total cost
        // by choosing an item which lies in
        // the interval L to R
        function maxTotalCost(arr,
            M, N, K)
        {
         
            // Stores the total maximum sum
            let totMaxSum = 0;
 
            for (let i = 1; i <= N; ++i) {
 
                // Stores the cost for ith item
                let currCost = [];
 
                for (let j = 0; j < M; ++j) {
 
                    // Check if the ith item
                    // belongs in the interval
                    if (arr[j][0] <= i
                        && arr[j][1] >= i) {
 
                        // Add the jth cost
                        currCost.push(arr[j][2]);
                    }
                }
 
                // Sort the currCost[] in the
                // non increasing order
                currCost.sort(function (a, b) { return b - a })
 
                // Stores the ith item sum
                let sum = 0;
 
                // Choose at most K costs
                for (let j = 0;
                    j < K
                    && j < currCost.length;
                    ++j) {
 
                    // Update the sum
                    sum += currCost[j];
                }
 
                // Update the totMaxSum
                totMaxSum = Math.max(totMaxSum, sum);
            }
 
            // Print the value of totMaxSum
            document.write(totMaxSum + '<br>');
        }
 
        // Driver Code
        let N = 10;
        let arr = [[2, 8, 800],
        [6, 9, 1500],
        [4, 7, 200],
        [3, 5, 400]];
        let M = arr.length;
        let K = 2;
 
        maxTotalCost(arr, M, N, K);
 
// This code is contributed by Potta Lokesh
    </script>


 
 

Output: 

2300

 

 

Time Complexity: O(N*M*log M)
Auxiliary Space: O(N*M)

 



Similar Reads

Count of index subsets such that maximum of values over these indices in A is at least total sum over B
Given two arrays A[] and B[] consisting of N positive integers, the task is to find the total number of subsets of indices such that the maximum value in the array A[] over all these indices is greater than or equal to the sum of all values over these indices in the array B[]. Examples: Input: A[] = {3, 1}, B[] = {1, 2}Output: 2Explanation:The tota
11 min read
Maximum time such that absolute difference between hour and minute lies in given range
Given a 24-hour time value, where on some numbers are question marks( '?' ), and two integers L and R. The question mark can be replaced with any number. The task is to find the maximum time such that the absolute difference between hour value and minute value lies in the interval [L, R]. If no possible value of time exists, then print -1. Examples
13 min read
Maximum length intersection of all K ranges among all given ranges
Given an array arr[] consisting of N ranges of the form [L, R], the task is to select K ranges such that the intersection length of the K ranges is maximum. Examples: Input: arr[] = {{5, 15}, {1, 10}, {14, 50}, {30, 70}, {99, 100}}, K = 2Output: 21Explanation: Selecting ranges (14, 50) and (30, 70) would give the maximum answer. Therefore, the maxi
7 min read
Check if a pair of integers from two ranges exists such that their Bitwise XOR exceeds both the ranges
Given two integers A and B, the task is to check if there exists two integers P and Q over the range [1, A] and [1, B] respectively such that Bitwise XOR of P and Q is greater than A and B. If found to be true, then print "Yes". Otherwise, print "No". Examples: Input: X = 2, Y = 2 Output: YesExplanation:By choosing the value of P and Q as 1 and 2 r
9 min read
Rearrange two given arrays such that sum of same indexed elements lies within given range
Given two arrays arr1[] and arr2[] consisting of N positive integers and an even integer K, the task is to check if the sum of the same indexed elements in the two arrays lie in the range [K/2, K] after rearranging the given arrays or not. If it is possible to obtain such an arrangement, then print "Yes". Otherwise, print "No". Examples: Input: arr
6 min read
Queries to check if a number lies in N ranges of L-R
Given N ranges and Q queries consisting of numbers. Every range consists of L and R. The task is to check if the given number lies in any of the given ranges or not for every query.Note: There is no overlapping range.Examples: Input: range[] = { {5, 6}, {1, 3}, {8, 10} Q = 4 1st query: 2 2nd query: 3 3rd query: 4 4th query: 7Output: Yes Yes No No1s
8 min read
Find two distinct numbers such that their LCM lies in given range
Given two numbers L and R, the task is to find two distinct minimum positive integers X and Y such that whose LCM lies in the range [L, R]. If there doesn't exist any value of X and Y then print "-1". Examples: Input: L = 3, R = 8 Output: x = 3, y=6Explanation:LCM of 3 and 6 is 6 which is in range 3, 8 Input: L = 88, R = 90Output: -1Explanation:Min
4 min read
Count of ways to select exactly K non-disjoint ranges from given N ranges
Given two arrays L[] and R[] of size N, and an integer K, the task is to find the number of ways to select exact K disjoint ranges formed by taking elements present at the same index from the array L[] and R[]. Examples: Input: N = 7, K = 3, L[] = {1, 3, 4, 6, 1, 5, 8}, R[] = {7, 8, 5, 7, 3, 10, 9}Output: 9Explanation: The possible ways of selectin
10 min read
Generate a pair of integers from a range [L, R] whose LCM also lies within the range
Given two integers L and R, the task is to find a pair of integers from the range [L, R] having LCM within the range [L, R] as well. If no such pair can be obtained, then print -1. If multiple pairs exist, print any one of them. Examples: Input: L = 13, R = 69Output: X =13, Y = 26Explanation: LCM(x, y) = 26 which satisfies the conditions L ? x &lt;
4 min read
Minimum absolute value of (K – arr[i]) for all possible values of K over the range [0, N – 1]
Given a positive integer N and a sorted array arr[] consisting of M integers, the task is to find the minimum absolute value of (K - arr[i]) for all possible values of K over the range [0, N - 1]. Examples: Input: N = 5, arr[] = {0, 4}Output: 0 1 2 1 0Explanation:Below are the possible minimum value for all possible values of K over the range [0, N
9 min read
Maximum range length such that A[i] is maximum in given range for all i from [1, N]
Given an array arr[] consisting of N distinct integers. For each i (0 ? i &lt; n), find a range [l, r] such that A[i] = max(A[l], A[l+1], ..., A[r]) and l ? i ? r and r-l is maximized. Examples: Input: arr[] = {1, 3, 2}Output: {0 0}, {0 2}, {2 2}Explanation: For i=0, 1 is maximum in range [0, 0] only. For i=1, 3 is maximum in range [0, 2] and for i
8 min read
Maximize cost of segment having weight at most K from given weight and cost of N items
Given two arrays W[] and C[] containing weight and cost of N (1 to N) items respectively, and an integer K, find a segment from 1 to N, such that the total weight of the segment is at most K and the total cost is maximum. Print the cost of this segment. Examples: Input: N = 6, K = 20, W[] = {9, 7, 6, 5, 8, 4}, C[] = {7, 1, 3, 6, 8, 3}Output: 17Expl
12 min read
Check if given point lies in range of any of the given towers
Given a 2D array arr[][] consisting of N rows of the form {Xi, Yi, Ri} such that (Xi, Yi) represents the position of a tower and Ri represents the network range of that tower. Given two integers X and Y, the task is to check if the point (X, Y) lies in the network range of the towers or not. Examples: Input: arr[][] = { {1, 1, 3}, {10, 10, 5}, {15,
7 min read
Count pairs from a given array whose product lies in a given range
Given an array arr[] of size N, and integers L and R, the task is to count the number of pairs [arri , arrj] such that i &lt; j and the product of arr[i] * arr[j] lies in the given range [L, R], i.e. L ? arr[i] * arr[j] ? R. Examples: Input: arr[ ] = {4, 1, 2, 5}, L = 4, R = 9Output: 3Explanation: Valid pairs are {4, 1}, {1, 5} and {4, 2}. Input: a
13 min read
Maximum sum of pair values such that value of pairs of same group should be a multiple of i in range [1, N]
Given an array of pairs arr[] of size N, where the first element of the pair is the value of the pair and the second element is the group at which this pair belongs, the task is to find the maximum sum of pair values, such that the number of pairs of the same group should be a multiple of i for all i in the range [1, N]. Examples: Input: arr[] = {{
13 min read
Split array into maximum subarrays such that every distinct element lies in a single subarray
Given an array, arr[] of size N, the task is to split the array into the maximum number of subarrays such that the first and the last occurrence of all distinct array element lies in a single subarray. Examples: Input: arr[] = {1, 1, 2, 2}Output: 2Explanation:Split the array into subarrays {1, 1} and {2, 2}.Therefore, the required output is 2. Inpu
6 min read
Find the most honest person from given statements of truths and lies
Given a binary matrix of size N * N, mat[][]. Value at cell (i, j) indicates what ith person says about jth person. A person x is considered honest if he always tells the truth. If person x speaks lie sometimes and truth sometimes, then he is a liar. If mat[i][j] = 0, then ith person says jth person is a liar.If mat[i][j] = 1, then ith person says
8 min read
Find if there exists a direction for ranges such that no two range intersect
Given N ranges [L, R] with velocities vel[]. The task is to assign each range a direction i.e. either left or right. All the ranges will start moving in the assigned direction at time t = 0. Find, if there is an assignment of directions possible given that no two ranges overlap at infinite time.Examples: Input: range[][] = {{1, 2}, {2, 5}, {3, 10},
8 min read
Find the GCD that lies in given range
Given two positive integer a and b and a range [low, high]. The task is to find the greatest common divisor of a and b which lie in the given range. If no divisor exist in the range, print -1.Examples: Input : a = 9, b = 27, low = 1, high = 5 Output : 3 3 is the highest number that lies in range [1, 5] and is common divisor of 9 and 27. Input : a =
7 min read
Count the number of intervals in which a given value lies
Given a 2D-array of [Tex]N [/Tex]integer intervals [Tex][L, R] [/Tex]and a value [Tex]V [/Tex]. For every interval [li, ri], the task is to check if V lies in between li and ri, both inclusive. The task is to print the count of intervals that satisfies this. Note: 1&lt;=li&lt;= riExamples: Input: arr[][] = {{1, 10}, {5, 10}, {15, 25}, {7, 12}, {20,
13 min read
Find a value X in range [0, K] which can maximize X XOR sum over given array
Given an array a[] of size N and an integer K, the task is to find a value X in the range [0, K] which can maximize the value of the given function Xor-sum(X) = (X XOR A[0]) + (X Xor A[1]) + (X Xor A[2]) + __________+ (X Xor A[N-1]). Examples: Input: a[] = {1, 2, 3, 4, 5, 6}, N=6, K=10Output: 8Explanation: The value of X is 1 for which the required
6 min read
Minimize cost to split an array into K subsets such that the cost of each element is its product with its position in the subset
Given an array arr[] of size N and a positive integer K, the task is to find the minimum possible cost to split the array into K subsets, where the cost of ith element ( 1-based indexing ) of each subset is equal to the product of that element and i. Examples: Input: arr[] = { 2, 3, 4, 1 }, K = 3 Output: 11 Explanation: Split the array arr[] into K
7 min read
Minimize cost to sort the Array by moving elements with cost as the value itself
Given an array arr[] of N positive integers, the task is to find the minimum cost to sort the given array by moving an array element to any position such that the cost of moving that element is the value of that element. Examples: Input: arr[] = {7, 1, 2, 3}Output: 6Explanation:Following are the possible set of moves to sort the array with minimum
9 min read
Find the remaining Array element after adding values in given ranges
Given an array A[] containing N elements and an array queries containing Q queries of type [ X, L, R ] where X is the element to be added to all the elements in the range [L, R]. After performing all Q queries keep on removing two array elements and append their sum into the array till the array size becomes 1. The task is to find this remaining ar
11 min read
Minimum cost to complete given tasks if cost of 1, 7 and 30 days are given
Given a sorted array arr[] consisting of N positive integers such that arr[i] represent the days in which a worker will work and an array cost[] of size 3 representing the salary paid to the workers for 1 day, 7 days and 30 days respectively, the task is to find the minimum cost required to have a worker for all the given days in arr[]. Examples: I
15+ min read
Maximum partitions possible of given Array with cost at most K and equal count of odd and even elements
Given two integers N, K, and an array, arr[] of size N, containing an equal number of even and odd elements, and also given that the cost of partitioning the array by making a cut between index i and i+1 is equal to the abs(arr[i]-arr[i+1]), the task is to find the maximum partitions of the array, such that each partition has an equal number of odd
9 min read
Remove elements from the array whose frequency lies in the range [l, r]
Given an array of integers, remove the elements from the array whose frequency lies in the range [l, r]. Examples: Input : arr[] = { 1, 2, 3, 3, 2, 2, 5 } l = 2, r = 3 Output : 1 5 We remove all those elements with frequencies from 2 to 5. Input : arr[] = { 1, 2, 3, 3, 3, 3 } l = 2, r = 3 Output : 3 3 3 3 Approach : Take a hash map, which will stor
5 min read
Array range queries over range queries
Given an array of size n and a give set of commands of size m. The commands are enumerated from 1 to m. These commands can be of the following two types of commands: Type 1 [l r (1 &lt;= l &lt;= r &lt;= n)] : Increase all elements of the array by one, whose indices belongs to the range [l, r]. In these queries of the index is inclusive in the range
15+ min read
Find a range that covers all the elements of given N ranges
Given N ranges containing L and R. The task is to check or find the index(0-based) of the range which covers all the other given N-1 ranges. If there is no such range, print -1. Note: All L and R points are distinct. Examples: Input: L[] = {1, 2}, R[] = {1, 2} Output: -1 Input: L[] = {2, 4, 3, 1}, R[] = {4, 6, 7, 9} Output: 3 Range at 3rd index i.e
5 min read
Find smallest range containing at least 1 elements from given N ranges
Given N ranges of the form [L, R], the task is to find the range having the minimum number of integers such that at least one point of all the given N ranges exists in that range. Example: Input: ranges[] = {{1, 6}, {2, 7}, {3, 8}, {4, 9}}Output: 6 6Explanation: All the given ranges contain 6 as an integer between them. Therefore, [6, 6] is a valid
7 min read
Article Tags :
three90RightbarBannerImg