File tree Expand file tree Collapse file tree 1 file changed +27
-0
lines changed Expand file tree Collapse file tree 1 file changed +27
-0
lines changed Original file line number Diff line number Diff line change @@ -99,6 +99,33 @@ public:
9999
100100
101101Java:
102+ ```java
103+ class Solution {
104+ public int largestSumAfterKNegations(int[] nums, int K) {
105+ // 将数组按照绝对值大小从大到小排序,注意要按照绝对值的大小
106+ nums = IntStream.of(nums)
107+ .boxed()
108+ .sorted((o1, o2) -> Math.abs(o2) - Math.abs(o1))
109+ .mapToInt(Integer::intValue).toArray();
110+ int len = nums.length;
111+ for (int i = 0; i < len; i++) {
112+ //从前向后遍历,遇到负数将其变为正数,同时K--
113+ if (nums[i] < 0 && k > 0) {
114+ nums[i] = -nums[i];
115+ k--;
116+ }
117+ }
118+ // 如果K还大于0,那么反复转变数值最小的元素,将K用完
119+ if (k % 2 == 1) nums[len - 1] = -nums[len - 1];
120+ int result = 0;
121+ for (int a : nums) {
122+ result += a;
123+ }
124+ return result;
125+ }
126+ }
127+ ```
128+
102129``` java
103130class Solution {
104131 public int largestSumAfterKNegations (int [] A , int K ) {
You can’t perform that action at this time.
0 commit comments