Created
May 7, 2019 18:31
-
-
Save priyankvex/8a3aee2ec341748d317ec8e7ac844a53 to your computer and use it in GitHub Desktop.
Maximum sum after K negations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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