Skip to content

Instantly share code, notes, and snippets.

@priyankvex
Created May 7, 2019 18:31
Show Gist options
  • Save priyankvex/8a3aee2ec341748d317ec8e7ac844a53 to your computer and use it in GitHub Desktop.
Save priyankvex/8a3aee2ec341748d317ec8e7ac844a53 to your computer and use it in GitHub Desktop.
Maximum sum after K negations
"""
https://scammingthecodinginterview.com
Week 3: Greedy
Problem: 3
"""
class Solution(object):
def solve(self, a, k):
a.sort()
index = 0
for num in a:
if num < 0 and index < k:
a[index] = -a[index]
index += 1
index = k - index
s = sum(a)
if index > 0:
index = index % 2
if index:
m = min(a)
s -= 2 * m
return s
if __name__ == "__main__":
a = [2, -3, -1, 5, -4]
k = 2
ans = Solution().solve(a, k)
print(ans)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment