Largest Ad Spend Rectangle That Stays Within a Budget Cap

Last updated: November 29, 2026

Quick Overview

Given an m x n grid of daily ad spend deltas (may be negative) and a budget k, return the largest sum of any axis-aligned sub-rectangle that is less than or equal to k.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Hard

0

0

0 solved


Given an m x n grid of daily ad spend deltas (may be negative) and a budget k, return the largest sum of any axis-aligned sub-rectangle that is less than or equal to k.

A Google onsite Hard problem grounded in Ads spend analysis. The interviewer expects you to compress the 2D problem to 1D by fixing row bounds, then solve 'max subarray sum at most k' with prefix sums and an ordered structure, and to pick which dimension to iterate over.

What the Interviewer Expects
  • Reduces to 1D by fixing a pair of rows and summing columns
  • Solves max subarray sum <= k with sorted prefix sums and binary search
  • Explains why Kadane alone does not respect the cap
  • Iterates over the smaller dimension for pairs
  • States O(min^2 * max * log(max)) time
Key Topics to Cover
Prefix Sums
Binary Search
Sorted Containers
Dimension Reduction
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • What if rows are many more than columns?
  • Use Kadane as a fast path: when is it valid?
  • Return the rectangle coordinates too.
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements
  • Input: grid m x n ints, integer k.
  • Output: maximum rectangle sum <= k. A solution is guaranteed to exist.
  • Values can be negative, which rules out two-pointer windows....
High-Level Design

Fix a top row and extend the bottom row, maintaining col_sum[c] for the strip. Now find the best contiguous column range with sum <= k. With prefix sums S, we want S[j] - S[i] <= k, maximized,...


Submit Your Answer
Markdown supported