Skip to content

Commit e1e1377

Browse files
1005 Maximize Sum Of Array After K Negations.py
1 parent ee811f2 commit e1e1377

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
#!/usr/bin/python3
2+
"""
3+
Given an array A of integers, we must modify the array in the following way: we
4+
choose an i and replace A[i] with -A[i], and we repeat this process K times in
5+
total. (We may choose the same index i multiple times.)
6+
7+
Return the largest possible sum of the array after modifying it in this way.
8+
9+
10+
11+
Example 1:
12+
13+
Input: A = [4,2,3], K = 1
14+
Output: 5
15+
Explanation: Choose indices (1,) and A becomes [4,-2,3].
16+
Example 2:
17+
18+
Input: A = [3,-1,0,2], K = 3
19+
Output: 6
20+
Explanation: Choose indices (1, 2, 2) and A becomes [3,1,0,2].
21+
Example 3:
22+
23+
Input: A = [2,-3,-1,5,-4], K = 2
24+
Output: 13
25+
Explanation: Choose indices (1, 4) and A becomes [2,3,-1,5,4].
26+
27+
28+
Note:
29+
30+
1 <= A.length <= 10000
31+
1 <= K <= 10000
32+
-100 <= A[i] <= 100
33+
"""
34+
from typing import List
35+
36+
37+
class Solution:
38+
def largestSumAfterKNegations(self, A: List[int], K: int) -> int:
39+
"""
40+
revert all the negative, if positive, revert multiple times the smallest
41+
42+
since -100 <= A[i] <= 100, then sort can be done in linear time
43+
"""
44+
A.sort()
45+
for i in range(len(A)):
46+
if K == 0:
47+
break
48+
49+
if A[i] < 0:
50+
A[i] *= -1
51+
prev = A[i]
52+
K -= 1
53+
else:
54+
if K % 2 != 0:
55+
if i - 1 >= 0 and A[i-1] < A[i]:
56+
A[i-1] *= -1
57+
else:
58+
A[i] *= -1
59+
break
60+
61+
return sum(A)

0 commit comments

Comments
 (0)