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

Commit aaa5c88

Browse files
Maximize Sum Of Array After K Negations
1 parent 174c77c commit aaa5c88

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
""" https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/ """
2+
3+
class Solution:
4+
def largestSumAfterKNegations(self, nums, k):
5+
minNum = min(nums)
6+
minNumIndex = nums.index(minNum)
7+
sum = 0
8+
9+
if (minNum < 0): # Negatif, Tek veya Çift
10+
nums[minNumIndex] *= -1
11+
k -= 1
12+
13+
while (k > 0) and (minNum < 0): # Negatifler pozitife dönüşene kadar.
14+
minNum = min(nums)
15+
minNumIndex = nums.index(minNum)
16+
nums[minNumIndex] *= -1
17+
k -= 1
18+
19+
if (k % 2 == 0): # Negatif ve Çift
20+
pass
21+
else: # Negatif ve Tek
22+
nums[minNumIndex] *= -1
23+
elif (minNum >= 0) and (k % 2 == 0): # Pozitif ve Çift
24+
pass
25+
elif (minNum >= 0) and (k % 2 == 1): # Pozitif ve Tek
26+
nums[minNumIndex] *= -1
27+
28+
for num in nums:
29+
sum += num
30+
31+
return sum
32+
33+
print(Solution().largestSumAfterKNegations([-2,5,0,2,-2], 3))

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /