|
| 1 | +#!/usr/bin/python3 |
| 2 | +""" |
| 3 | +Given an array A of integers, we must modify the array in the following way: we |
| 4 | +choose an i and replace A[i] with -A[i], and we repeat this process K times in |
| 5 | +total. (We may choose the same index i multiple times.) |
| 6 | +
|
| 7 | +Return the largest possible sum of the array after modifying it in this way. |
| 8 | +
|
| 9 | +
|
| 10 | +
|
| 11 | +Example 1: |
| 12 | +
|
| 13 | +Input: A = [4,2,3], K = 1 |
| 14 | +Output: 5 |
| 15 | +Explanation: Choose indices (1,) and A becomes [4,-2,3]. |
| 16 | +Example 2: |
| 17 | +
|
| 18 | +Input: A = [3,-1,0,2], K = 3 |
| 19 | +Output: 6 |
| 20 | +Explanation: Choose indices (1, 2, 2) and A becomes [3,1,0,2]. |
| 21 | +Example 3: |
| 22 | +
|
| 23 | +Input: A = [2,-3,-1,5,-4], K = 2 |
| 24 | +Output: 13 |
| 25 | +Explanation: Choose indices (1, 4) and A becomes [2,3,-1,5,4]. |
| 26 | +
|
| 27 | +
|
| 28 | +Note: |
| 29 | +
|
| 30 | +1 <= A.length <= 10000 |
| 31 | +1 <= K <= 10000 |
| 32 | +-100 <= A[i] <= 100 |
| 33 | +""" |
| 34 | +fromtypingimportList |
| 35 | + |
| 36 | + |
| 37 | +classSolution: |
| 38 | +deflargestSumAfterKNegations(self,A:List[int],K:int)->int: |
| 39 | +""" |
| 40 | + revert all the negative, if positive, revert multiple times the smallest |
| 41 | +
|
| 42 | + since -100 <= A[i] <= 100, then sort can be done in linear time |
| 43 | + """ |
| 44 | +A.sort() |
| 45 | +foriinrange(len(A)): |
| 46 | +ifK==0: |
| 47 | +break |
| 48 | + |
| 49 | +ifA[i]<0: |
| 50 | +A[i]*=-1 |
| 51 | +prev=A[i] |
| 52 | +K-=1 |
| 53 | +else: |
| 54 | +ifK%2!=0: |
| 55 | +ifi-1>=0andA[i-1]<A[i]: |
| 56 | +A[i-1]*=-1 |
| 57 | +else: |
| 58 | +A[i]*=-1 |
| 59 | +break |
| 60 | + |
| 61 | +returnsum(A) |