Orchard harvest trips
HardOnline Assessment
Plan the cheapest cart trips to bring in an orchard row's apple harvest.
crates is a string with one digit per tree along a row, in walking order: the digit is the number of crates of ripe apples waiting at that tree ("0" to "9"). A single cart collects them in trips. Each trip walks along a run of consecutive trees (at least one tree), picks up everything at those trees, and brings it to the packing shed. Every tree must belong to exactly one trip, and trips cover the row from left to right.
A trip that carries L crates in total costs L * L + setup effort: the cart gets harder to push the fuller it is, and every trip pays a fixed setup to harness up and reach the shed. Trees with 0 crates still have to be part of some trip, but add nothing to its load.
Input: crates, a string of digits; setup, a non-negative integer.
Output: the minimum total effort over all ways to split the row into trips. An empty row needs no trips, so return 0.
The row can have thousands of trees, so trying every possible first and last tree of every trip will be too slow.
Example 1
- Input:
- ["3333",20]
- Output:
- 112
- Explanation
- Four trees with 3 crates each and a 20-effort setup. One trip of 12 crates costs 144 + 20; four single-tree trips cost 4 * (9 + 20) = 116; two trips of 6 crates cost 2 * (36 + 20) = 112, which is the best split.
Example 2
- Input:
- ["9009",50]
- Output:
- 262
- Explanation
- Only the two end trees have crates, 9 each, with
setup50. The cheapest plan is two trips with 9 crates each, such as"9"+"009"or"900"+"9", for 2 * (81 + 50) = 262. One trip carrying all 18 crates would cost 324 + 50 = 374.
Example 3
- Input:
- ["0000",7]
- Output:
- 7
- Explanation
- There are no crates at all, so a single trip with load 0 costs only the setup: 7. Four separate trips would cost 28.
Constraints
0 <= crates.length <= 12,000- every character of
cratesis a digit from"0"to"9" 0 <= setup <= 1,000,000- the answer fits comfortably in a 64-bit integer