Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions 1005.maximize-sum-of-array-after-k-negations.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/* URL of this problem
* https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/description/
*
* @param {number[]} nums
* @param {number} k
* @return {number}
*/

var largestSumAfterKNegations = function(nums, k) {
const ModifiedNums = [...nums];
let minNum = Math.min(...ModifiedNums);
let minNumIdx = ModifiedNums.indexOf(minNum);
let repeat = k;

while (minNum < 0 && repeat > 0) {
ModifiedNums[minNumIdx] *= -1;

minNum = Math.min(...ModifiedNums);
minNumIdx = ModifiedNums.indexOf(minNum);
repeat--;
}

// Convert the minimum negative number to the positive one by multiplying -1 to maximize the sum of numbers
// if the conversion still needs to be done, which is that repeat is odd
if (repeat % 2 === 1) {
ModifiedNums[minNumIdx] *= -1;
}

return ModifiedNums.reduce((sum, curr) => {
return sum + curr
}, 0);
};

module.exports = largestSumAfterKNegations;
17 changes: 17 additions & 0 deletions largestSumAfterKNegations.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
const largestSumAfterKNegations = require("../jest-test/1005.maximize-sum-of-array-after-k-negations");

test("Return the sum of nums after converting the minmum number", () => {
expect(largestSumAfterKNegations([3,-1,0,2], 3)).toBe(6);
});

test("Return the sum of nums after converting the first k minmum numbers", () => {
expect(largestSumAfterKNegations([2,-3,-1,5,-4], 2)).toBe(13);
});

test("Return 0 if nums consists of 0s", () => {
expect(largestSumAfterKNegations([0,0,0], 2)).toBe(0);
});

test("Return Infinity if nums is empty", () => {
expect(largestSumAfterKNegations([], 2)).toBe(0);
});