mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
添加(1005.K次取反后最大化的数组和.md):增加typescript版本
This commit is contained in:
@ -211,5 +211,29 @@ var largestSumAfterKNegations = function(nums, k) {
|
|||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### TypeScript
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function largestSumAfterKNegations(nums: number[], k: number): number {
|
||||||
|
nums.sort((a, b) => Math.abs(b) - Math.abs(a));
|
||||||
|
let curIndex: number = 0;
|
||||||
|
const length = nums.length;
|
||||||
|
while (curIndex < length && k > 0) {
|
||||||
|
if (nums[curIndex] < 0) {
|
||||||
|
nums[curIndex] *= -1;
|
||||||
|
k--;
|
||||||
|
}
|
||||||
|
curIndex++;
|
||||||
|
}
|
||||||
|
while (k > 0) {
|
||||||
|
nums[length - 1] *= -1;
|
||||||
|
k--;
|
||||||
|
}
|
||||||
|
return nums.reduce((pre, cur) => pre + cur, 0);
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||||
|
Reference in New Issue
Block a user