[Swift Weekly Contest 127]LeetCode1005. K 次取反后最大化的数组和 | Maximize Sum Of Array After K Negations

[Swift Weekly Contest 127]LeetCode1005. K 次取反后最大化的数组和 | Maximize Sum Of Array After K Negations,第1张

概述Given an array A of integers, we must modify the array in the following way: we choose an i and replace A[i] with -A[i], and we repeat this process K times in total.  (We may choose the same index i m

Given an array A of integers,we must modify the array in the following way: we choose an i and replace A[i] with -A[i],and we repeat this process K times in total.  (We may choose the same index i multiple times.)

Return the largest possible sum of the array after modifying it in this way. 

Example 1:

input: A = [4,2,3],K = 1 Output: 5 Explanation: Choose indices (1,) and A becomes [4,-2,3]. 

Example 2:

input: A = [3,-1,2],K = 3 Output: 6 Explanation: Choose indices (1,2) and A becomes [3,1,2]. 

Example 3:

input: A = [2,-3,5,-4],K = 2 Output: 13 Explanation: Choose indices (1,4) and A becomes [2,3,4]. 

Note:

1 <= A.length <= 10000 1 <= K <= 10000 -100 <= A[i] <= 100

给定一个整数数组 A,我们只能用以下方法修改该数组:我们选择某个个索引 i 并将 A[i] 替换为 -A[i],然后总共重复这个过程 K 次。(我们可以多次选择同一个索引 i。)

以这种方式修改数组后,返回数组可能的最大和。 

示例 1:

输入:A = [4,K = 1输出:5解释:选择索引 (1,) ,然后 A 变为 [4,3]。

示例 2:

输入:A = [3,K = 3输出:6解释:选择索引 (1,2) ,然后 A 变为 [3,2]。

示例 3:

输入:A = [2,K = 2输出:13解释:选择索引 (1,4) ,然后 A 变为 [2,4]。 

提示:

1 <= A.length <= 10000 1 <= K <= 10000 -100 <= A[i] <= 100 Runtime: 44 ms Memory Usage: 19.1 MB
 1 class Solution { 2     func largestSumAfterKNegations(_ A: [Int],_ K: Int) -> Int { 3         var A = A 4         var K = K 5         A.sort() 6         for i in 0..<A.count 7         { 8             if K > 0 && A[i] < 0 9             {10                 A[i] = -A[i]11                 K -= 1                12             }13         }14         A.sort()15         if K % 2 == 116         {17             A[0] = -A[0]18         }19         var ret:Int = 020         for a in A21         {22            ret += a 23         }24         return ret25     }26 }
总结

以上是内存溢出为你收集整理的[Swift Weekly Contest 127]LeetCode1005. K 次取反后最大化的数组和 | Maximize Sum Of Array After K Negations全部内容,希望文章能够帮你解决[Swift Weekly Contest 127]LeetCode1005. K 次取反后最大化的数组和 | Maximize Sum Of Array After K Negations所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1018794.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-23
下一篇 2022-05-23

发表评论

登录后才能评论

评论列表(0条)

保存