Social feed~25 min2s · 256 MBtarget O(R × C) time, O(C) spaceclassic twin: lc-931dp
A photo app in a social feed shrinks a picture by one column of pixels. It removes a seam: one pixel from every row. Each pixel sits in the same column as the one above it, or one column to the left or right. Every pixel has an energy that says how much it stands out.
Your team lead asks: "What is the lowest total energy of any seam from the top row to the bottom row?"
Write lowest_seam(energy).
energy[r][c] is the energy of the pixel in row r, column c. Every row has the same length.r + 1 is in column c - 1, c or c + 1, where c is the column of the pixel in row r, and the column must exist.Input: energy = [[3, 5, 2, 6], [4, 1, 7, 2], [6, 3, 1, 5], [2, 8, 4, 1]]
Output: 5Let seam[r][c] be the lowest total energy of a seam that ends at pixel (r, c). It came from column c - 1, c or c + 1 of the row above, so take the smallest of those that exist and add this pixel's energy.
The first row costs its own energy.
| Row | Column 0 | Column 1 | Column 2 | Column 3 |
|---|---|---|---|---|
| 0 | 3 | 5 | 2 | 6 |
| 1 | 7 (min of 3, 5 + 4) | 3 (min of 3, 5, 2 + 1) | 9 (min of 5, 2, 6 + 7) | 4 (min of 2, 6 + 2) |
| 2 | 9 (min of 7, 3 + 6) | 6 (min of 7, 3, 9 + 3) | 4 (min of 3, 9, 4 + 1) | 9 (min of 9, 4 + 5) |
| 3 | 8 (min of 9, 6 + 2) | 12 (min of 9, 6, 4 + 8) | 8 (min of 6, 4, 9 + 4) | 5 (min of 4, 9 + 1) |
The smallest number in the last row is 5, so the lowest seam energy is 5.
Input: energy = [[4], [2], [9]]
Output: 15One column: the seam is the whole column, 4 + 2 + 9.
Input: energy = [[5, 1, 7]]
Output: 1One row: the seam is a single pixel, so take the lowest energy, 1.
1 ≤ rows ≤ 300 and 1 ≤ cols ≤ 300, and every row has the same length.0 ≤ energy[r][c] ≤ 1,000A picture of 300 by 300 pixels has 90,000 pixels. A seam has up to 3 choices in each of 300 rows, which is about 3 to the power 300 seams. A table with one entry for each pixel takes about 90,000 small steps.