Untitled
unknown
java
3 years ago
2.4 kB
8
Indexable
import java.util.*; public class StockExchange { public static List<Transaction> transactions(List<Offer> orders) { // Create two lists to store sell and buy offers List<Offer> sellOffers = new ArrayList<>(); List<Offer> buyOffers = new ArrayList<>(); // Split offers into sell and buy lists for (Offer offer : orders) { if (offer.type.equals("müük")) { sellOffers.add(offer); } else { buyOffers.add(offer); } } // Sort sell offers by price in ascending order and buy offers by price in descending order sellOffers.sort(Comparator.comparingInt(o -> o.price)); buyOffers.sort(Comparator.comparingInt(o -> o.price).reversed()); // Initialize the result list List<Transaction> res = new ArrayList<>(); // Iterate through sell and buy offers and perform transactions int i = 0, j = 0; while (i < sellOffers.size() && j < buyOffers.size()) { Offer sellOffer = sellOffers.get(i); Offer buyOffer = buyOffers.get(j); if (sellOffer.price <= buyOffer.price) { int quantity = Math.min(sellOffer.quantity, buyOffer.quantity); res.add(new Transaction(quantity, sellOffer.price)); sellOffer.quantity -= quantity; buyOffer.quantity -= quantity; if (sellOffer.quantity == 0) { i++; } if (buyOffer.quantity == 0) { j++; } } else { break; } } return res; } public static void main(String[] args) { List<Offer> orders = Arrays.asList( new Offer("sell", 10, 100), new Offer("sell", 20, 110), new Offer("buy", 10, 90), new Offer("buy", 15, 115), new Offer("buy", 10, 105) ); List<Transaction> res = transactions(orders); System.out.println(res); // Output: [(10,100), (5,110)] } } class Offer { String type; int quantity; int price; public Offer(String type, int quantity, int price) { this.type = type; this.quantity = quantity; this.price = price; } } class Transaction { int quantity; int price; public Transaction(int quantity, int price) { this.quantity = quantity; this.price = price; } @Override public String toString() { return "(" + quantity + "," + price + ")"; } }
Editor is loading...