From 63e2a42d5b60220f064a241a4a6f85e3536d8baf Mon Sep 17 00:00:00 2001 From: LiangDazhu <42199191+LiangDazhu@users.noreply.github.com> Date: Sat, 15 May 2021 00:04:20 +0800 Subject: [PATCH] =?UTF-8?q?Update=201005.K=E6=AC=A1=E5=8F=96=E5=8F=8D?= =?UTF-8?q?=E5=90=8E=E6=9C=80=E5=A4=A7=E5=8C=96=E7=9A=84=E6=95=B0=E7=BB=84?= =?UTF-8?q?=E5=92=8C.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Added python version code --- .../1005.K次取反后最大化的数组和.md | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/problems/1005.K次取反后最大化的数组和.md b/problems/1005.K次取反后最大化的数组和.md index 1653201e..89ed9176 100644 --- a/problems/1005.K次取反后最大化的数组和.md +++ b/problems/1005.K次取反后最大化的数组和.md @@ -124,7 +124,18 @@ class Solution { ``` Python: - +```python +class Solution: + def largestSumAfterKNegations(self, A: List[int], K: int) -> int: + A = sorted(A, key=abs, reverse=True) # 将A按绝对值从大到小排列 + for i in range(len(A)): + if K > 0 and A[i] < 0: + A[i] *= -1 + K -= 1 + if K > 0: + A[len(A) - 1] *= ((-1)**K) + return sum(A) +``` Go: @@ -135,4 +146,4 @@ Go: * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) * B站视频:[代码随想录](https://space.bilibili.com/525438321) * 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ) -