Ctrl K

Spend the Most Across Shops

Hard
There are m shops, each with n items on its shelf. shelves[i][j] is the base price of item j in shop i; on every shelf prices go from expensive to cheap: shelves[i][j] ≥ shelves[i][j + 1]. You buy exactly one item per day. On day d (days are numbered from 1) you pick any shop that still has items and must take the **rightmost** item left on its shelf, paying shelves[i][j] · d. After m · n days you have bought everything. Return the largest total amount you can spend.
Example 1
shelves=[[5, 2], [4, 3]] → 40

Day 1: the 2 from shop 0 (2 · 1). Day 2: the 3 from shop 1 (3 · 2). Day 3: the 4 (4 · 3). Day 4: the 5 (5 · 4). Total 2 + 6 + 12 + 20 = 40.

Example 2
shelves=[[9, 1], [2, 2]] → 47

Buy the 1 first, then both 2s from shop 1, and save the most expensive item for the last day: 1 + 4 + 6 + 36 = 47.

Constraints
  • 1 ≤ m = len(shelves) ≤ 10
  • 1 ≤ n = len(shelves[i]) ≤ 10⁴
  • 1 ≤ shelves[i][j] ≤ 10⁶
  • each row shelves[i] is non-increasing
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsBest Picks From Capped Shelves MediumGrowing Capital Project by Project HardMost Orders by Their Deadlines HardNarrowest Range Touching Every List HardCrew Paid by Skill Hard
loading Python…
Input
shelves=[[5, 2], [4, 3]]
Expected
40

Run checks the first 3 tests in your browser. Submit checks all 61 tests on the server, hidden ones included.