Social feed~25 min2s · 256 MBtarget O(n²) time, O(n²) spaceclassic twin: lc-486dp
A feed app builds a weekly digest from a row of posts, and each post has engagement points. Two curators choose posts in turns. On a turn, a curator must take the first or the last post still in the row.
The first curator starts. Both want the larger total, and both play as well as they can. Your team lead asks: "Does the first curator end with at least as many points as the second?"
Write first_curator_wins(points).
points[i] is the engagement of the post at position i.true when the first curator can finish with a total at least as large as the second curator's total. A tie counts as a win for the first curator.Input: points = [4, 7, 2, 9, 5]
Output: falseLet lead[i][j] be how many points more than the other curator the curator to move can collect from posts i to j. A range of one post gives that post's points. A longer range gives the better of two moves. Take the left post and subtract the lead the opponent then has, or do the same with the right post.
We fill the ranges from short to long.
| Length | Range 0 | Range 1 | Range 2 | Range 3 | Range 4 |
|---|---|---|---|---|---|
| 1 | 4 | 7 | 2 | 9 | 5 |
| 2 | 3 | 5 | 7 | 4 | |
| 3 | -1 | 4 | -2 | ||
| 4 | 10 | 9 | |||
| 5 | -5 |
Here "range i" starts at post i. The whole row is range 0 of length 5, and its lead is -5. The first curator ends 5 points behind, so the answer is false.
Input: points = [8, 5, 8]
Output: trueThe first curator takes 8, the second takes 8 or 5, and the first curator takes the other side. The first curator ends with 13 or more against 8 or less.
Input: points = [5, 5]
Output: trueEach curator takes 5, so the totals tie, and a tie is a win for the first curator.
1 ≤ len(points) ≤ 1,0000 ≤ points[i] ≤ 1,000Every move has 2 choices, so the number of games grows as 2 to the power of the row length. A row of 1,000 posts is far too long to play out. Table entries are about n²/2, which is 500,500 for n = 1,000, and each needs two reads. A square-order table is affordable.