Merge pull request #1215 from xiaofei-2020/greed09

添加(1005.K次取反后最大化的数组和.md):增加typescript版本
This commit is contained in:
程序员Carl
2022-05-02 10:32:59 +08:00
committed by GitHub

View File

@ -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>