Maximize Sum Of Array After K Negations

  • choose an index i and replace nums[i] with -nums[i].
Input: nums = [4,2,3], k = 1
Output: 5
Explanation: Choose index 1 and nums becomes [4,-2,3].
Input: nums = [3,-1,0,2], k = 3
Output: 6
Explanation: Choose indices (1, 2, 2) and nums becomes [3,1,0,2].
Input: nums = [2,-3,-1,5,-4], k = 2
Output: 13
Explanation: Choose indices (1, 4) and nums becomes [2,3,-1,5,4]
def largestSumAfterKNegations(nums,k):
nums.sort()
i=0
while(True):
if(i>=len(nums) or nums[i]>0 or k<=0):
break
if(nums[i]<0 and k>0):
nums[i]=-1*nums[i]
k-=1
i+=1
nums.sort()
if(k==0):
return sum(nums)
else:
if(0 in nums):
return sum(nums)
else:
if(k%2!=0):
nums[0]=nums[0]*-1
return sum(nums)
say, nums = [2,-3,-1,5,-4], k = 2ater step 1 negation 

nums=[2,3,-1,5,-4]
after second negation
nums=[2,3,-1,5,4]

sum is 2+3-1+5+4 =13

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Dhanarajappu

Dhanarajappu

Tech-Enthusiast, Coder,Explorer,Geeky,Software Engineer |A piece of code delivers everything that you need. The world is all about codes.