PracHub
QuestionsCoachesLearningGuidesInterview Prep

Quick Overview

This question evaluates resource allocation, combinatorial optimization, and online/streaming algorithm design within the Coding & Algorithms domain, requiring reasoning about assigning weight‑constrained cargo to flights under timing and cost constraints; it is commonly asked to assess algorithmic thinking about trade-offs between revenue and booking cost, constraint satisfaction, and handling dynamic inputs. The problem tests both conceptual understanding of optimization and online decision‑making and practical application skills for implementing incremental processing and robust handling of failed bookings.

  • hard
  • Optiver
  • Coding & Algorithms
  • Software Engineer

Optimize flight and cargo bookings for profit

Company: Optiver

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: hard

Interview Round: Onsite

## OptiCargo: make the booking algorithm profitable You are given two streams/lists: - **Flights** you may attempt to book. Each flight has: - `flight_id` - `depart_time` and `arrive_time` - `max_weight` (capacity) - `cost` (paid only if you successfully book the flight) - **Cargo jobs** you may book. Each cargo has: - `cargo_id` - `weight` - `latest_arrival_time` (deadline) - `revenue` (earned if delivered by the deadline) A cargo job can be assigned to **at most one** booked flight. A flight can carry multiple cargo jobs as long as total assigned weight ≤ `max_weight`. A cargo job is deliverable on a flight if `arrive_time ≤ latest_arrival_time`. ### Task A (batch / fix existing code) The existing implementation is unprofitable because it books **all** flights regardless of whether there is profitable cargo to carry. Design/implement changes so that the algorithm chooses which flights to book and which cargo to assign to maximize **total profit**: \[ \text{profit} = \sum(\text{revenue of delivered cargo}) - \sum(\text{cost of booked flights}) \] You may output either: - the maximum profit value, or - the set of booked flights and cargo-to-flight assignments. ### Task B (incremental / streaming class) Implement a class that processes events as they arrive: - `onFlight(flight)` adds a new available flight. - `onCargo(cargo)` adds a new available cargo job. - Optionally, `decide()` (or similar) updates the plan. At any time, the class should be able to report the current planned profit and/or current bookings/assignments. ### Realism constraint (booking may fail) When you “apply” to book a flight, the booking can fail (e.g., another party booked it first). Your design should handle failed bookings gracefully (e.g., retry, re-plan, or treat it as removed from availability).

Quick Answer: This question evaluates resource allocation, combinatorial optimization, and online/streaming algorithm design within the Coding & Algorithms domain, requiring reasoning about assigning weight‑constrained cargo to flights under timing and cost constraints; it is commonly asked to assess algorithmic thinking about trade-offs between revenue and booking cost, constraint satisfaction, and handling dynamic inputs. The problem tests both conceptual understanding of optimization and online decision‑making and practical application skills for implementing incremental processing and robust handling of failed bookings.

Part 1: Maximize Opticargo profit for a fixed set of flights and cargo

Given a fixed set of **flights** and **cargo orders**, assign cargo to flights to **maximize total profit**. Each flight is a dedicated shipment slot that, if booked, carries **at most one** cargo order, and each cargo can be shipped on **at most one** flight. Implement: ```python def solution(flights, cargos): ``` ## Input format - **`flights`** — a list of flights. Each flight is a 3-element array `[departure_time, max_weight, cost]`: - `departure_time` — when the flight departs - `max_weight` — the most weight the flight can carry - `cost` — the cost of booking the flight - **`cargos`** — a list of cargo orders. Each cargo is a 3-element array `[weight, latest_arrival, revenue]`: - `weight` — the cargo's weight - `latest_arrival` — the latest time the cargo may arrive - `revenue` — the revenue earned by delivering the cargo Either list may be empty. ## Feasibility rule In this simplified model **delivery is instantaneous**. A cargo `j` can be assigned to a flight `i` **if and only if** both conditions hold: 1. `flights[i].departure_time <= cargos[j].latest_arrival` 2. `flights[i].max_weight >= cargos[j].weight` ## Profit If cargo `j` is assigned to flight `i`, that pairing contributes profit: ``` revenue_j - cost_i ``` ## Rules - You may **skip** any flight or any cargo — leaving a flight unbooked or a cargo unshipped contributes `0`. - **Never take a loss-making booking when skipping is better.** Because skipping is always allowed, a feasible pair whose `revenue_j - cost_i` is **not positive** should never be booked (it contributes `0`, same as skipping). - A flight can be matched to at most one cargo, and a cargo to at most one flight (the assignment is a one-to-one matching between a subset of flights and a subset of cargos). ## Output Return the **maximum total profit** achievable over all valid assignments, as an integer. If no profitable booking exists (including when either list is empty), return `0`. ## Constraints - `0 <= len(flights), len(cargos) <= 80` - `1 <= departure_time, latest_arrival, max_weight, weight, cost, revenue <= 10^9` - Each flight can be used at most once. - Each cargo can be shipped at most once.

Constraints

  • 0 <= len(flights), len(cargos) <= 80
  • 1 <= departure_time, latest_arrival, max_weight, weight, cost, revenue <= 10^9
  • Each flight can be used at most once
  • Each cargo can be shipped at most once

Examples

Input: ([(1, 10, 100), (3, 5, 30)], [(4, 3, 90), (5, 1, 120), (6, 5, 140)])

Expected Output: 100

Explanation: Assign cargo (4, 3, 90) to flight (3, 5, 30) for profit 60, and cargo (6, 5, 140) to flight (1, 10, 100) for profit 40. Total profit is 100.

Input: ([(2, 3, 50)], [(4, 5, 100), (3, 1, 100)])

Expected Output: 0

Explanation: One cargo is too heavy and the other misses the time constraint, so no profitable shipment is possible.

Hints

  1. Think of flights and cargo orders as the two sides of a bipartite graph. A feasible pair has weight max(0, revenue - cost).
  2. Because skipping is allowed, you can add dummy nodes with profit 0 and solve a maximum-weight matching problem.

Part 2: Streaming Opticargo planner with updates and profit queries

Build a **streaming cargo-to-flight profit planner**: process a list of `operations` that arrive over time and, for every `QUERY` operation, return the **current maximum total profit** achievable by assigning the active cargos to the active flights. ## What to implement ```python def solution(operations): ... ``` `operations` is a list of operations (each is a tuple/list whose first element is the operation name). Return a list of integers — **one answer per `QUERY`**, in the order the queries occur. ## State You maintain two collections that change as operations are processed: - **Active flights**, each identified by a string `flight_id`. - **Active cargos**, each identified by a string `cargo_id`. ## Operations Each operation is one of the following (argument order matters): | Operation | Form | Effect | |-----------|------|--------| | Add flight | `('ADD_FLIGHT', flight_id, departure_time, max_weight, cost)` | Make the flight active. | | Add cargo | `('ADD_CARGO', cargo_id, weight, latest_arrival, revenue)` | Make the cargo active. | | Remove flight | `('REMOVE_FLIGHT', flight_id)` | Make that flight inactive. | | Remove cargo | `('REMOVE_CARGO', cargo_id)` | Make that cargo inactive. | | Query | `('QUERY',)` | Append the current maximum total profit to the output. | **Update semantics:** - **Re-adding an existing id replaces** the previously active record that has the same id (the newest attributes win). - **Removing a non-existent id is a no-op** (do nothing, no error). ## Shipment model (same as Part 1) At any query, you assign cargos to flights subject to: - **Each active flight carries at most one active cargo**, and **each active cargo uses at most one flight** (a one-to-one matching). Any flight or cargo may also be left unassigned. - A cargo can be carried by a flight **only if both** of the following hold: - `departure_time <= latest_arrival`, and - `max_weight >= weight`. - The **profit** of carrying a cargo on a flight is `revenue - cost`. A match whose profit is **not positive** (`revenue - cost <= 0`) is never worth making and should be treated as contributing **0** — equivalently, only assign a cargo to a flight when doing so strictly increases total profit. The answer for a query is the **maximum total profit** over all valid assignments of the current active flights and cargos. If there are no profitable matches (or no active flights/cargos), the answer is **0**. ## Output Return the list of query answers in order. The maximum total profit is always `>= 0`. ## Constraints - `0 <= len(operations) <= 200` - At any `QUERY`, the number of active flights and the number of active cargos are each at most `60`. - `1 <= departure_time, latest_arrival, max_weight, weight, cost, revenue <= 10^9` - `flight_id` and `cargo_id` are strings. - Re-adding an existing id replaces the previously active item with that id. ## Example ``` operations = [ ('ADD_FLIGHT', 'F1', 1, 10, 100), ('ADD_CARGO', 'C1', 4, 3, 90), ('QUERY',), -> 0 ('ADD_CARGO', 'C2', 6, 5, 140), ('QUERY',), -> 40 ('ADD_FLIGHT', 'F2', 3, 5, 30), ('QUERY',), -> 100 ] # returns [0, 40, 100] ``` At the first query, only F1 and C1 are active: F1 can carry C1 (`1 <= 3` and `10 >= 4`), but the profit is `90 - 100 = -10`, which is not positive, so the best total is `0`. After adding C2, F1 can carry C2 for `140 - 100 = 40`. After adding F2, F1↔C2 (`40`) plus F2↔C1 (`90 - 30 = 60`) gives a total of `100`.

Constraints

  • 0 <= len(operations) <= 200
  • At any QUERY, the number of active flights and active cargos is at most 60 each
  • 1 <= departure_time, latest_arrival, max_weight, weight, cost, revenue <= 10^9
  • flight_id and cargo_id are strings
  • Re-adding an existing id replaces the previous active item

Examples

Input: [('ADD_FLIGHT', 'F1', 1, 10, 100), ('ADD_CARGO', 'C1', 4, 3, 90), ('QUERY',), ('ADD_CARGO', 'C2', 6, 5, 140), ('QUERY',), ('ADD_FLIGHT', 'F2', 3, 5, 30), ('QUERY',)]

Expected Output: [0, 40, 100]

Explanation: With only F1 and C1, shipping loses money so the best profit is 0. After adding C2, F1 can profitably ship it for 40. After adding F2, the best matching becomes 100.

Input: [('ADD_FLIGHT', 'F1', 1, 5, 5), ('ADD_FLIGHT', 'F2', 2, 10, 20), ('ADD_CARGO', 'C1', 5, 2, 40), ('ADD_CARGO', 'C2', 10, 2, 50), ('QUERY',), ('REMOVE_CARGO', 'C2'), ('QUERY',), ('REMOVE_FLIGHT', 'F1'), ('QUERY',)]

Expected Output: [65, 35, 20]

Explanation: The best matching first uses both flights. After removing C2, only C1 remains and F1 is the better choice. After removing F1, only F2 can ship C1.

Hints

  1. Keep the currently active flights and cargos in dictionaries keyed by id.
  2. Because the active set is small, you can recompute the best offline matching from scratch on every QUERY.
Last updated: Apr 19, 2026

Loading coding console...

PracHub

Master your tech interviews with 8,500+ real questions from top companies.

Product

  • Questions
  • Learning Tracks
  • Interview Guides
  • Resources
  • Premium
  • For Universities

Browse

  • By Company
  • By Role
  • By Category
  • Topic Hubs
  • SQL Questions
  • AI Coding Questions
  • Compare Platforms
  • Discord Community

Support

  • support@prachub.com
  • (916) 541-4762

Legal

  • Privacy Policy
  • Terms of Service
  • About Us

© 2026 PracHub. All rights reserved.

Related Coding Questions

  • Maintain Price Levels For A Single-Symbol Order Book - Optiver (medium)
  • Calculate Days Between Arbitrary Gregorian Dates - Optiver (medium)
  • Build and Validate a Binary Tree from Parent-Child Pairs - Optiver (medium)
  • Days Between Two Calendar Dates - Optiver (medium)
  • Thread-Safe Stock Inventory: Buy and Sell Without Overselling - Optiver (medium)