반응형
난이도 - Medium
Intuition
Code
class Solution:
def minimumOperationsToWriteY(self, grid: List[List[int]]) -> int:
n = len(grid)
y_area = 2* (n//2) + (n//2 + 1)
others_area = n*n - y_area
counter_y = defaultdict(int)
counter_others = defaultdict(int)
for i in range(n):
for j in range(n):
counter_others[grid[i][j]] += 1
# The diagoanl starting at the top-left cell
for i in range(n//2):
counter_y[grid[i][i]] += 1
counter_others[grid[i][i]] -= 1
# The diagoanl starting at the top-right cell
for i in range(n//2):
counter_y[grid[i][n-i-1]] += 1
counter_others[grid[i][n-i-1]] -= 1
# The vertical line starting at the center cell
for i in range(n//2, n):
counter_y[grid[i][n//2]] += 1
counter_others[grid[i][n//2]] -= 1
ans = float('inf')
for y in [0,1,2]:
for o in [0,1,2]:
if y == o:
continue
y_to_change = y_area - counter_y[y]
others_to_change = others_area - counter_others[o]
ans = min(ans, y_to_change + others_to_change)
return ans
Complexity
Time Complexity: O(N^2)
Space Complexity: O(1)
반응형
'코딩 알고리즘 문제 > Leetcode' 카테고리의 다른 글
| 15. 3Sum (Array, Two Pointers, Sorting) (0) | 2025.10.27 |
|---|---|
| 210. Course Schedule II (Depth-First Search, Breadth-First Search, Graph, Topological Sort) (0) | 2025.10.27 |
| 739. Daily Temperatures (Array, Stack, Monotonic Stack) (0) | 2025.10.27 |
| 886. Possible Bipartition (Depth-First Search, Breadth-First Search, Union Find, Graph) (0) | 2025.10.27 |
| 974. Subarray Sums Divisible by K (0) | 2025.10.27 |