My first instinct was just BFS every cell and try flipping each zero, which works but is way too slow for a 500x500 grid.
First, identify all existing islands and label each cell with its island ID and area. Then, for each 0 cell, compute the sum of areas of distinct neighboring islands (up to 4) and take the maximum; also consider the case of no flip (max existing island area).
Pro tip: Mention edge cases upfront: all 1s (return n*n), all 0s (return 1), and single row/column. This shows thoroughness and often impresses interviewers.
Confirm the problem constraints and discuss edge cases like all 1s, all 0s, and 1x1 matrix. This ensures you cover all scenarios.
Use BFS/DFS or Union-Find to label each island with a unique ID and compute its area. Store the area in a map or array.
For each 0, collect the distinct island IDs of its 4 neighbors, sum their areas, and add 1 for the flipped cell. Track the maximum.
Also consider the maximum island area without flipping any 0, as flipping might not always increase the area (e.g., all 1s).
Return the larger of the maximum area from flipping a 0 and the maximum existing island area.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.