Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commite1e1377

Browse files
1005 Maximize Sum Of Array After K Negations.py
1 parentee811f2 commite1e1377

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+
fromtypingimportList
35+
36+
37+
classSolution:
38+
deflargestSumAfterKNegations(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+
foriinrange(len(A)):
46+
ifK==0:
47+
break
48+
49+
ifA[i]<0:
50+
A[i]*=-1
51+
prev=A[i]
52+
K-=1
53+
else:
54+
ifK%2!=0:
55+
ifi-1>=0andA[i-1]<A[i]:
56+
A[i-1]*=-1
57+
else:
58+
A[i]*=-1
59+
break
60+
61+
returnsum(A)

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp