1005. Leecode Maximize Sum Of Array After K Negations
关键词:贪心
思路:
- 排序或者用函数库min,找到数组最小值。
- 每次只要将最小值去负,直到用完K次。
解答:
var largestSumAfterKNegations = function(A, K) {
if (!A || A.length == 0 || K == 0) return 0;
while (K > 0){
let min = Math.min(...A);
let minIndex = A.indexOf(min);
A[minIndex] = -A[minIndex];
K--;
}
return A.reduce((acce, cur)=> acce + cur);
};