← Back to list

Solving HackerRank Problem | Buy Sell Orders to Maximize Profit

Problem statement

Naman Kumar Sinha · 2026-01-18 09:12 · 0 claps · 2.1 min read
#buy-sell-orders #data-structures #hackerrank-solution #problem-solving #profit-maximization
Open on Medium ↗

Solving HackerRank Problem | Buy Sell Orders to Maximize Profit

Problem statement

You are given a list of buy and sell orders for a product. Each order is represented as a string in the format:

[id, price, TYPE, quantity]

  • id: unique identifier for the order (not used for profit calculation)
  • price: price per unit
  • TYPE: either "BUY" or "SELL"
  • quantity: number of units

Rules:

  • You can only sell if there is a matching buy order.
  • The profit for each matched unit is calculated as (buy price - sell price) * quantity.
  • Always match the lowest sell price with the highest buy price available.
  • You must maximize profit by matching orders optimally.

Return the total profit.

Example — Inputs 11,20,SELL,300, 12,30,BUY,260, 10,20,BUY,230

Explanation:

  • There are two BUY orders: 260 units at 30, 230 units at 20.
  • One SELL order: 300 units at 20.
  • Match the highest BUY price (30) with SELL price (20) for as many units as possible.
  • 260 units can be matched at profit (30–20) 260 = 10 260 = 2600
  • Remaining SELL quantity: 300–260 = 40 units
  • Next highest BUY price is 20, but SELL price is also 20, so profit is 0 for these units. Since BUY price = SELL price we cannot profit .
  • For profit to occur BUY price > SELL price

Total profit = 2600 + 0 = 2600

Approach :

  • Parse orders into BUY and SELL lists.
  • Sort BUYs descending, SELLs ascending.
  • Match highest BUY with lowest SELL for as many units as possible.
  • Calculate profit for each match.
  • Return total profit.
package hackerrank;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class BuySellOrder {

    public static void main(String[] args) {
//        List<String> orders = Arrays.asList(
//                "[11,20,SELL,300]",
//                "[12,30,BUY,260]",
//                "[10,20,BUY,230]"
//        );
        List<String> orders = Arrays.asList(
                "[1,50,SELL,100]",
                "[2,60,BUY,50]",
                "[3,55,BUY,70]",
                "[4,50,SELL,30]"
        );
// Matching: multiple buy and sell
// - 50 units: BUY at 60, SELL at 50 → profit = 10*50 = 500
// - 50 units: BUY at 55, SELL at 50 → profit = 5*50 = 250
// - 20 units: BUY at 55, SELL at 50 → profit = 5*20 = 100
// Total profit: 500 + 250 + 100 = 850
        System.out.println(getProfit(orders));
    }

    private static int getProfit(List<String> orders) {
        List<int []> buys = new ArrayList<>();
        List<int []> sells = new ArrayList<>();

        for(String order: orders){
            String [] parts = order.replace("[","").replace("]","").split(",");
            int id = Integer.parseInt(parts[0].trim());
            int price = Integer.parseInt(parts[1].trim());
            String type = parts[2].trim();
            int qty = Integer.parseInt(parts[3].trim());
            if (type.equals("BUY")) {
                buys.add(new int[]{price, qty});
            } else {
                sells.add(new int[]{price, qty});
            }
        }
        // Sort buys descending by price, sells ascending by price
        buys.sort((a, b) -> b[0] - a[0]);
        sells.sort(Comparator.comparingInt(a -> a[0]));

        for (int[] buy : buys) {
            System.out.println("BuyPrice: " + buy[0] + ", Quantity: " + buy[1]);
        }
        for (int[] sell : sells) {
            System.out.println("SellPrice: " + sell[0] + ", Quantity: " + sell[1]);
        }

        int profit = 0;
        int buyIdx = 0, sellIdx = 0;
        while (buyIdx < buys.size() && sellIdx < sells.size()) {
            int buyPrice = buys.get(buyIdx)[0];
            int buyQty = buys.get(buyIdx)[1];
            int sellPrice = sells.get(sellIdx)[0];
            int sellQty = sells.get(sellIdx)[1];

            if (buyPrice > sellPrice) {
                int matchedQty = Math.min(buyQty, sellQty);
                profit += (buyPrice - sellPrice) * matchedQty;
                buys.get(buyIdx)[1] -= matchedQty;
                sells.get(sellIdx)[1] -= matchedQty;
                if (buys.get(buyIdx)[1] == 0) buyIdx++;
                if (sells.get(sellIdx)[1] == 0) sellIdx++;
            } else {
                // No profit possible, move to next buy order
                buyIdx++;
            }
        }
        return profit;
    }
}

메타데이터
post_id
910b934c14e2
slug
solving-hackerrank-problem-buy-sell-orders-to-maximize-profit-910b934c14e2
url
https://medium.com/@namansinha_38977/solving-hackerrank-problem-buy-sell-orders-to-maximize-profit-910b934c14e2
canonical_url
https://medium.com/@namansinha_38977/solving-hackerrank-problem-buy-sell-orders-to-maximize-profit-910b934c14e2
author_url
https://medium.com/@namansinha_38977
status
ok
fetched_at
2026-07-20 13:22:34