485. Maximum Delivery Route Earnings
Maximum Delivery Route Earnings

A delivery company has depots connected by two-way roads that form a binary tree. Each depot has an earning amount: positive values add money, while negative values represent costs.

Input list and delivery tree with the best route highlighted

Find the maximum earnings from one delivery route. Start and finish at any depot, follow connected roads, and never visit a depot twice. A route must visit at least one depot; visiting just one is allowed. Add the amounts at every visited depot, including both endpoints. The route need not include the root.

Method Signature

int bestRouteEarnings(List<String> depotEarnings)
  • depotEarnings: the binary tree encoded as described below.
  • Return only the maximum total earnings, even when that total is negative.

Input Format

The list stores the tree in level order. The first entry is the root. For each existing depot, processed in level order, the next two entries describe its left and right children.

Each entry is an integer string or "#", which means a missing child. Missing children have no child entries. Trailing missing-child entries may be omitted.

Constraints

  • The list represents a valid, non-empty binary tree, and its first entry is an integer string.
  • Number of depots: 1 ≤ count ≤ 30,000.
  • Each depot's amount: -1,000 ≤ amount ≤ 1,000.
  • The list and all its entries are non-null.

Examples

Example 1

Method call: bestRouteEarnings(depotEarnings = ["5", "-3", "7", "8", "2", "-4", "6"])

Output: 23

Explanation: Choose the route with amounts 8 → -3 → 5 → 7 → 6, totaling 23.

Example 2

Method call: bestRouteEarnings(depotEarnings = ["-15", "4", "10", "#", "#", "-2", "9", "7", "3"])

Output: 24

Explanation: Choose 7 → -2 → 10 → 9, totaling 24. This route excludes the root.

Example 3

Method call: bestRouteEarnings(depotEarnings = ["-8", "-2", "-6"])

Output: -2

Explanation: Visiting only the depot with amount -2 gives the highest total.



Please use Laptop/Desktop or any other large screen to add/edit code.