Maximum Spending After Buying Items - Problem

You are given a 0-indexed m × n integer matrix values, representing the values of m × n different items in m different shops. Each shop has n items where the jth item in the ith shop has a value of values[i][j].

Additionally, the items in the ith shop are sorted in non-increasing order of value. That is, values[i][j] >= values[i][j + 1] for all 0 <= j < n - 1.

On each day, you would like to buy a single item from one of the shops. Specifically, on the dth day you can:

  • Pick any shop i
  • Buy the rightmost available item j for the price of values[i][j] × d

That is, find the greatest index j such that item j was never bought before, and buy it for the price of values[i][j] × d.

Note that all items are pairwise different. For example, if you have bought item 0 from shop 1, you can still buy item 0 from any other shop.

Return the maximum amount of money that can be spent on buying all m × n products.

Input & Output

Example 1 — Basic 2×2 Matrix
$ Input: values = [[8,5],[9,4]]
Output: 74
💡 Note: Items available: 8,5,9,4. Optimal strategy: buy smallest items first to save larger values for later days with higher multipliers. Day 1: buy 4×1=4, Day 2: buy 5×2=10, Day 3: buy 8×3=24, Day 4: buy 9×4=36. Total: 4+10+24+36=74
Example 2 — Single Row
$ Input: values = [[10,8,6,4,2]]
Output: 110
💡 Note: One shop with 5 items in decreasing order. Buy in reverse order: Day 1: buy 2×1=2, Day 2: buy 4×2=8, Day 3: buy 6×3=18, Day 4: buy 8×4=32, Day 5: buy 10×5=50. Total: 2+8+18+32+50=110
Example 3 — Single Column
$ Input: values = [[5],[3],[4]]
Output: 23
💡 Note: Three shops with one item each: 5,3,4. Sort: [3,4,5]. Day 1: buy 3×1=3, Day 2: buy 4×2=8, Day 3: buy 5×3=15. Total: 3+8+15=26

Constraints

  • 1 ≤ m, n ≤ 1000
  • 1 ≤ values[i][j] ≤ 106
  • values[i][j] ≥ values[i][j + 1] for all valid i, j

Visualization

Tap to expand
Maximum Spending Strategy: Buy Small Items FirstShop Matrix8594Input valuesOptimal StrategySort all items:[4, 5, 8, 9]Buy smallest first!Greedy approachDaily PurchasesDay 1: 4 × 1 = 4Day 2: 5 × 2 = 10Day 3: 8 × 3 = 24Day 4: 9 × 4 = 36Max total: 74❌ Wrong: Buy expensive items first → smaller total✅ Correct: Buy cheap items first → maximum total
Understanding the Visualization
1
Input Matrix
2D matrix with item values, each row sorted descending
2
Strategy
Buy cheapest items first to save expensive items for later days
3
Result
Maximum total spending achieved
Key Takeaway
🎯 Key Insight: Buy cheapest items first so expensive items get multiplied by larger day numbers
Asked in
Google 35 Amazon 28 Microsoft 22 Meta 18
23.4K Views
Medium Frequency
~25 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen