1. 程式人生 > >[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

ret 輸入 leetcode runtime exp The fyi swift odi

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,0,2], K = 3
Output: 6
Explanation: Choose indices (1, 2, 2) and A becomes [3,1,0,2].

Example 3:

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

Note:

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

給定一個整數數組 A,我們只能用以下方法修改該數組:我們選擇某個個索引 i 並將 A[i] 替換為 -A[i],然後總共重復這個過程 K 次。(我們可以多次選擇同一個索引 i。)

以這種方式修改數組後,返回數組可能的最大和。

示例 1:

輸入:A = [4,2,3], K = 1
輸出:5
解釋:選擇索引 (1,) ,然後 A 變為 [4,-2,3]。

示例 2:

輸入:A = [3,-1,0,2], K = 3
輸出:6
解釋:選擇索引 (1, 2, 2) ,然後 A 變為 [3,1,0,2]。

示例 3:

輸入:A = [2,-3,-1,5,-4], K = 2
輸出:13
解釋:選擇索引 (1, 4) ,然後 A 變為 [2,3,-1,5,4]。 

提示:

  1. 1 <= A.length <= 10000
  2. 1 <= K <= 10000
  3. -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 == 1
16         {
17             A[0] = -A[0]
18         }
19         var ret:Int = 0
20         for a in A
21         {
22            ret += a 
23         }
24         return ret
25     }
26 }

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