1359. Pickup Deliveries
Count All Valid Pickup and Delivery Options
Another wonderful bottom up DP training.
A bit simpler than problem 552.
At least that's how I feel.
Base Case
With only one order, there's only one valid arrangement: pickup first (P), then delivery (D), giving a count of 1.
It looks like this: .
Observing the Path Upward 🧗
1. How to Place and
must always appear to the left of . This is our problem's requirement.
So let's first figure out where can go.
The sequence has 3 slots where can insert itself.
Once is placed, 4 slots are formed. However, at 's perspective, they vary:
I. Place before : 1 + 3 format
Left side of : slots to the left of
Right side of : slots to the right of
II. Place between and : 2 + 2 format
III. Place after : 3 + 1 format
Since must always be to the left of , once is placed, can only go into slots to the right, which are those on the right of .
Total valid slots for : .
So with 2 orders, our count is .
2. Generalizing to and for
When and are about to be inserted, there are already orders in front,
forming a sequence of length , from which thus has slots to choose.
From left to right, number of valid slots available to after placing is respectively.
This is an arithmetic series summing to , the exact multiplier applied to previous count when arranging and .
Thereby, our state transition equation is:
Time to write the code 🧑🏻💻👩🏻💻
As always, numbers can get astronomically large. Don't forget to apply modulo.
- C++
- Python
#include <cmath>
using namespace std;
int countValidSequences(int totalOrders) // LeetCode Q.1359.
{
long long modulo = pow(10, 9) + 7; // Long long prevents overflow.
// Base case when n is 1: pickup 1 followed by delivery 1.
long long validSequences = 1;
for (int prevOrderNum = 1; prevOrderNum <= totalOrders - 1; prevOrderNum++) {
int spotsCount = 2 * prevOrderNum + 1;
// Sum from 1 to spots count.
int multiple = spotsCount * (spotsCount + 1) / 2;
validSequences *= multiple;
validSequences %= modulo;
}
return validSequences;
}
def count_valid_sequences(total_orders: int) -> int: # LeetCode Q.1359.
modulo = 10 ** 9 + 7
# Base case when n is 1: pickup 1 followed by delivery 1.
valid_sequences = 1
for prev_order_num in range(1, total_orders):
spots_count = 2 * prev_order_num + 1
# Sum from 1 to spots count.
multiple = spots_count * (spots_count + 1) // 2
valid_sequences *= multiple
valid_sequences %= modulo
return valid_sequences
time, space. Be sure to practice writing the transition equation by hand too.