Open In App

Find Maximum Profit for Products within Budget

Last Updated : 08 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given a 2D integer array product, where product[i] = [costi, profiti] represents the cost and profit of a product, respectively. Additionally, you have been given a 0-indexed integer array called budget[]. For each budget[i], the task is to find the maximum profit of a product whose cost is less than or equal to budget[i]. If no such product exists, then the answer to this query would be 0.

Example:

Input: product = {{2,3}, {3,6}, {4,1}, {7,12}, {4,7}}, budget = {2,3,4,6,7,8}
Output: {3,6,7,7,12,12}
Explanation:

  • For budget{0} = 2, {2,3} is the only product. Hence, the maximum profit is 3.
  • For budget{1} = 3, the products which can be considered are {2,3}, {3,6}. The maximum profit among them is 6.
  • For budget{2} = 4, the products which can be considered are {2,3}, {3,6}, {4,1}, {4,7}. The maximum profit among them is 7.
  • For budget{3} = 6, the products which can be considered are {2,3}, {3,6}, {4,1}, {4,7}. The maximum profit among them is 7.
  • For budget{4} = 7 and budget{5}= 8, all products can be considered. Hence, the answer for this query is the maximum profit of all products, i.e., 12.

Input: product = {{40,22}, {20,6}}, budget = {10,5}
Output: {0,0}
Explanation: For budget{0} = 10 and budget{1} = 5, none of the products can be considered because the cost of all products is more than the available budget. Hence, the maximum profit for these queries is 0.

Approach:

The idea is to sort the product array in ascending order based on the cost value. Then update each product’s profit to be the maximum of its own profit and the profit of the previous products. This ensures that for any product, it’s profit is the maximum profit among all products with equal or lesser cost. For each budget[i], the binary search function finds the maximum profit of a product whose cost is less than or equal to budgets[i].

Step-by-step algorithm:

  • Create a binary search function to find the index of the highest product less than or equal to a given value.
  • Sort the product[][] vector based on product cost in ascending order.
  • Update profit values to store the maximum of current and previous values.
  • Calculate maximum profit for each budget using conditional checks and binary search.
  • Return the vector containing maximum profit for each budget.

Below is the implementation of the above algorithm:

C++




// C++ Code
#include <bits/stdc++.h>
using namespace std;
 
// Function to perform binary search on the 'product' vector
// and return the index of the highest product that is less
// than or equal to 'x'.
int binarySearch(int x, vector<vector<int> >& product)
{
    int l = 0, h = product.size() - 1;
    while (l < h) {
        int m = (l + h + 1) / 2;
        if (product[m][0] == x) {
            // Return 'm' if it is at the last index or
            // index of last occurrence of 'x'
            if (m == product.size() - 1
                || product[m][0] != product[m + 1][0])
                return m;
            // else continue searching for the last
            // occurrence of 'x'
            else
                l = m;
        }
        else if (product[m][0] < x)
            l = m;
        else
            h = m - 1;
    }
    // return the index of greatest element less than 'x'
    return l;
}
 
// Function to calculate the maximum profit for each budget
vector<int>
maximumprofproduct(vector<vector<int> >& product,
                vector<int>& budget)
{
    int n = product.size();
    sort(begin(product), end(product));
 
    // Store the maximum of current and previous values
    for (int i = 1; i < n; i++)
        product[i][1]
            = max(product[i - 1][1], product[i][1]);
 
    vector<int> ans;
    for (int i = 0; i < budget.size(); i++) {
        // if the budget[i] is less than lowest value insert
        // 0
        if (budget[i] < product[0][0])
            ans.push_back(0);
 
        // if the budget[i] is grater than highest value
        // inset the maximum value
        else if (budget[i] >= product[n - 1][0])
            ans.push_back(product[n - 1][1]);
 
        // Find the maximum profit of a product whose cost
        // is less than or equal to budgets[i] using binary
        // search
        else
            ans.push_back(product[binarySearch(
                budget[i], product)][1]);
    }
 
    // Return the answer vector
    return ans;
}
 
// Driver code
int main()
{
    // Test case 1
    vector<vector<int> > product = {
        { 2, 3 }, { 3, 6 }, { 4, 1 }, { 7, 12 }, { 4, 7 }
    };
    vector<int> budget = { 2, 3, 4, 6, 7, 8 };
    vector<int> answer
        = maximumprofproduct(product, budget);
    for (auto i : answer)
        cout << i << " ";
 
    return 0;
}


Java




// Java code
import java.util.*;
 
public class Main {
    // Function to perform binary search on the 'product'
    // array and return the index of the highest product
    // that is less than or equal to 'x'.
    public static int bsearch(int x, int[][] product)
    {
        int l = 0, h = product.length - 1;
        while (l < h) {
            int m = (l + h + 1) / 2;
            if (product[m][0] == x) {
                // Return 'm' if it is at the last index or
                // index of last occurrence of 'x'
                if (m == product.length - 1
                    || product[m][0] != product[m + 1][0])
                    return m;
                // else continue searching for the last
                // occurrence of 'x'
                else
                    l = m;
            }
            else if (product[m][0] < x)
                l = m;
            else
                h = m - 1;
        }
        // return the index of greatest element less than
        // 'x'
        return l;
    }
 
    // Function to calculate the maximum profit for each
    // budget
    public static int[] maximumprofproduct(int[][] product,
                                           int[] budget)
    {
        int n = product.length;
        Arrays.sort(product,
                    Comparator.comparingInt(a -> a[0]));
 
        // Store the maximum of current and previous values
        for (int i = 1; i < n; i++)
            product[i][1] = Math.max(product[i - 1][1],
                                     product[i][1]);
 
        int[] ans = new int[budget.length];
        for (int i = 0; i < budget.length; i++) {
            // if the budget[i] is less than lowest value
            // insert 0
            if (budget[i] < product[0][0])
                ans[i] = 0;
            // if the budget[i] is greater than highest
            // value insert the maximum value
            else if (budget[i] >= product[n - 1][0])
                ans[i] = product[n - 1][1];
            // Find the maximum profit of a product whose
            // cost is less than or equal to budgets[i]
            // using binary search
            else
                ans[i] = product[bsearch(budget[i],
                                         product)][1];
        }
 
        // Return the answer array
        return ans;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        // Test case 1
        int[][] product = { { 2, 3 },
                             { 3, 6 },
                             { 4, 1 },
                             { 7, 12 },
                             { 4, 7 } };
        int[] budget = { 2, 3, 4, 6, 7, 8 };
        int[] answer
            = maximumprofproduct(product, budget);
        for (int i : answer)
            System.out.print(i + " ");
        System.out.println();
 
         
    }
}


C#




using System;
using System.Collections.Generic;
using System.Linq;
 
class Program
{
    // Function to perform binary search on the 'product' list
    // and return the index of the highest product that is less
    // than or equal to 'x'.
    static int BinarySearch(int x, List<List<int>> product)
    {
        int l = 0, h = product.Count - 1;
        while (l < h)
        {
            int m = (l + h + 1) / 2;
            if (product[m][0] == x)
            {
                // Return 'm' if it is at the last index or
                // index of last occurrence of 'x'
                if (m == product.Count - 1 || product[m][0] != product[m + 1][0])
                    return m;
                // else continue searching for the last
                // occurrence of 'x'
                else
                    l = m;
            }
            else if (product[m][0] < x)
                l = m;
            else
                h = m - 1;
        }
        // return the index of greatest element less than 'x'
        return l;
    }
 
    // Function to calculate the maximum profit for each budget
    static List<int> MaximumProfitProduct(List<List<int>> product, List<int> budget)
    {
        int n = product.Count;
        product = product.OrderBy(p => p[0]).ToList();
 
        // Store the maximum of current and previous values
        for (int i = 1; i < n; i++)
            product[i][1] = Math.Max(product[i - 1][1], product[i][1]);
 
        List<int> ans = new List<int>();
        for (int i = 0; i < budget.Count; i++)
        {
            // if the budget[i] is less than lowest value insert
            // 0
            if (budget[i] < product[0][0])
                ans.Add(0);
 
            // if the budget[i] is greater than highest value
            // insert the maximum value
            else if (budget[i] >= product[n - 1][0])
                ans.Add(product[n - 1][1]);
 
            // Find the maximum profit of a product whose cost
            // is less than or equal to budgets[i] using binary
            // search
            else
                ans.Add(product[BinarySearch(budget[i], product)][1]);
        }
 
        // Return the answer list
        return ans;
    }
 
    // Driver code
    static void Main()
    {
        // Test case 1
        List<List<int>> product = new List<List<int>> {
            new List<int> { 2, 3 }, new List<int> { 3, 6 },
            new List<int> { 4, 1 }, new List<int> { 7, 12 },
            new List<int> { 4, 7 }
        };
        List<int> budget = new List<int> { 2, 3, 4, 6, 7, 8 };
 
        List<int> answer = MaximumProfitProduct(product, budget);
        foreach (var i in answer)
            Console.Write(i + " ");
 
        // Keep the console window open in debug mode.
        Console.ReadKey();
    }
}


Javascript




function binarySearch(x, product) {
    let l = 0, h = product.length - 1;
    while (l < h) {
        let m = Math.floor((l + h + 1) / 2);
        if (product[m][0] === x) {
            // Return 'm' if it is at the last index or
            // index of last occurrence of 'x'
            if (m === product.length - 1 || product[m][0] !== product[m + 1][0]) {
                return m;
            }
            // else continue searching for the last
            // occurrence of 'x'
            else {
                l = m;
            }
        } else if (product[m][0] < x) {
            l = m;
        } else {
            h = m - 1;
        }
    }
    // Return the index of the greatest element less than 'x'
    return l;
}
 
function maximumProfProduct(product, budget) {
    const n = product.length;
    product.sort((a, b) => a[0] - b[0]);
 
    // Store the maximum of current and previous values
    for (let i = 1; i < n; i++) {
        product[i][1] = Math.max(product[i - 1][1], product[i][1]);
    }
 
    const ans = [];
    for (const b of budget) {
        // If budget is less than the lowest value, insert 0
        if (b < product[0][0]) {
            ans.push(0);
        }
        // If budget is greater than or equal to the highest value, insert the maximum value
        else if (b >= product[n - 1][0]) {
            ans.push(product[n - 1][1]);
        }
        // Find the maximum profit of a product whose cost is less than or equal
        // to the budget using binary search
        else {
            ans.push(product[binarySearch(b, product)][1]);
        }
    }
 
    // Return the answer list
    return ans;
}
 
// Test case
const product = [
    [2, 3], [3, 6], [4, 1], [7, 12], [4, 7]
];
const budget = [2, 3, 4, 6, 7, 8];
const answer = maximumProfProduct(product, budget);
console.log(...answer);


Python3




def binary_search(x, product):
    l, h = 0, len(product) - 1
    while l < h:
        m = (l + h + 1) // 2
        if product[m][0] == x:
            # Return 'm' if it is at the last index or
            # index of last occurrence of 'x'
            if m == len(product) - 1 or product[m][0] != product[m + 1][0]:
                return m
            # else continue searching for the last
            # occurrence of 'x'
            else:
                l = m
        elif product[m][0] < x:
            l = m
        else:
            h = m - 1
    # Return the index of the greatest element less than 'x'
    return l
 
def maximum_prof_product(product, budget):
    n = len(product)
    product.sort()
 
    # Store the maximum of current and previous values
    for i in range(1, n):
        product[i][1] = max(product[i - 1][1], product[i][1])
 
    ans = []
    for b in budget:
        # If budget is less than the lowest value, insert 0
        if b < product[0][0]:
            ans.append(0)
        # If budget is greater than or equal to the highest value, insert the maximum value
        elif b >= product[n - 1][0]:
            ans.append(product[n - 1][1])
        # Find the maximum profit of a product whose cost is less than or equal to the budget using binary search
        else:
            ans.append(product[binary_search(b, product)][1])
 
    # Return the answer list
    return ans
 
# Driver code
if __name__ == "__main__":
    # Test case
    product = [
        [2, 3], [3, 6], [4, 1], [7, 12], [4, 7]
    ]
    budget = [2, 3, 4, 6, 7, 8]
    answer = maximum_prof_product(product, budget)
    print(*answer)
     
# This code is contributed by shivamgupta310570


Output

3 6 7 7 12 12 


Time Complexity: O(n*log(n))
Auxiliary Space: O(n)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads