Skip to content

Commit 9008b15

Browse files
committed
2025-06-20
1 parent 968c553 commit 9008b15

2 files changed

Lines changed: 52 additions & 0 deletions

File tree

algorithm/基础算法/贪心.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@
4040
- [1432. 改变一个整数能得到的最大差值](/leetcode/4-每日一题/1432.%20改变一个整数能得到的最大差值.md)
4141
- [2966. 划分数组并满足最大差限制](/leetcode/4-每日一题/2966.%20划分数组并满足最大差限制.md)
4242
- [2294. 划分数组使最大差为 K](/leetcode/4-每日一题/2294.%20划分数组使最大差为%20K.md)
43+
- [3443. K 次修改后的最大曼哈顿距离](/leetcode/4-每日一题/3443.%20K%20次修改后的最大曼哈顿距离.md)
4344

4445
## 5. 优缺点
4546

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
# [3443. K 次修改后的最大曼哈顿距离](https://leetcode.cn/problems/maximum-manhattan-distance/description/)
2+
3+
> **日期**:2025-06-20
4+
> **所用时间**:10min
5+
6+
## 1. 贪心
7+
8+
思路:
9+
1. 曼哈顿距离 = $|x1-x2| + |y1-y2|$
10+
2. 对于每个方向,统计移动次数:
11+
- N: y坐标增加
12+
- S: y坐标减少
13+
- E: x坐标增加
14+
- W: x坐标减少
15+
3. 贪心策略:
16+
- 优先抵消相反方向的移动(NS, EW)
17+
- 剩余修改次数用于增加距离
18+
4. 对于每个位置,计算:
19+
- 当前NS方向的最大距离 + 当前EW方向的最大距离
20+
- 取所有位置的最大值
21+
22+
关键点:
23+
- 每次修改可以改变一个字符的方向
24+
- 要最大化曼哈顿距离,需要让x和y方向的差值尽可能大
25+
- 通过抵消相反方向,然后用剩余修改次数增加距离
26+
27+
**复杂度分析**
28+
29+
- 时间复杂度: $O(n)$
30+
- 空间复杂度: $O(1)$
31+
32+
**Python3**
33+
34+
```python
35+
class Solution:
36+
def maxDistance(self, ss: str, k: int) -> int:
37+
def count(a, b, k):
38+
return abs(a - b) + 2 * k
39+
40+
ans = n = s = e = w = 0
41+
for c in ss:
42+
if c == 'N': n += 1
43+
elif c == 'S': s += 1
44+
elif c == 'E': e += 1
45+
elif c == 'W': w += 1
46+
47+
cnt1 = min(n, s, k)
48+
cnt2 = min(w, e, k - cnt1)
49+
ans = max(ans, count(n, s, cnt1) + count(w, e, cnt2))
50+
return ans
51+
```

0 commit comments

Comments
 (0)