I have an approach, but I cannot proof it is correct.
Lets pretend a 0 means no square at the given position, a 1 means a 1x1 square at the given position, a 2 means a 2x2 square at the given position and so on. We obviously don’t have any 2’s or higher, but that does not mean we cannot add them ourselves.
So I would start by counting all 1’s, which is our initial cost. Then I try to place a 2x2 square in any position of our grid, and if the resulting cost is at least equal (or lower) to our current cost, I write that number inside a new matrix. And then copy all 1’s that are not covered by 2’s. Then repeat for 3’s, 4’s, …, n’s
Example:
max size: 1x1 - total cost: 16
1 1 0 0 0 0 0 1 1
1 1 0 0 0 0 0 1 1
0 1 1 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 1 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 1 1
0 0 0 0 0 0 0 1 1
max size: 2x2 - total cost: 10
2 0 0 0 0 0 0 2 0
0 2 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 1 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 2 0
0 0 0 0 0 0 0 0 0
max size: 3x3 - total cost: 9
3 0 0 0 0 0 0 2 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 1 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 2 0
0 0 0 0 0 0 0 0 0
max size: 4x4 - total cost: 9
4 0 0 0 0 0 0 2 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 2 0
0 0 0 0 0 0 0 0 0
Example 2 (worst case for 4x4)
max size: 1x1 - total cost: 16
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1
max size: 2x2 - total cost: 18
2 2 2 0
2 2 2 0
2 2 2 0
0 0 0 0
max size: 3x3 - total cost: 12
3 3 0 0
3 3 0 0
0 0 0 0
0 0 0 0
max size: 4x4 - total cost: 4
4 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
Edit 1: I am uncertain about the time complexity. If we brute forced literally everything, we would end up with O(N³ * log N) I think.
Edit 3: I played around with excel, the brute force time complexity is O(N³*log N). In the case of N = 50, it is lower than O(50^3 * ln 50 * 2)
Edit 2: Also note that the total cost can increase if you try a step from i → i+1. This only means the cost will later come down again, because of a heavy overlap.