leetcode 1005 Maximize Sum Of Array After K Negations & leetcode 1006 Clumsy Factorial

leetcode 1005

Sort the array first.

The negation rules are quite simple:

  1. execute negation for K times,so use a for loop
  2. after negation, if the next number (if has) is smaller, the next number is next to negation (if still in for loop). Here we use a greedy strategy. If the next number is non-negative and smaller than the current one, negation it will result in less sum loss(for example current is 4, and next is 1), if the next number is negative and smaller than the current one, negation it will result in more sum (for example current is 4 and next is -3).

After that , compute the sum.

class Solution {
    public int largestSumAfterKNegations(int[] A, int K) {
        Arrays.sort(A);
        int idx = 0;
        for (int i = 0; i < K; ++i) {
            A[idx] = -A[idx];
            if (idx + 1 < A.length) {
                if (A[idx + 1] < A[idx]) idx += 1;
            }
        }
        int sum = 0;
        for (int i = 0; i < A.length; ++i) sum += A[i];
        return sum;
    }
}

leetcode 1006

Use brute-force way. Code seems quite ugly but works fine. The complexity is O(n)

    public int clumsy(int N) {
        int ret = 0;
        int flag = 1;
        for (;N > 0;) {
            if (N == 1) {
                ret += (flag * N);
                break;
            }
            else if (N == 2) {
                ret += (flag * N * (N - 1));
                break;
            }
            else if (N == 3) {
                ret += flag * ((N * (N - 1)) / (N - 2));
                break;
            }
            else {
                ret = ret + flag * ((N * (N - 1)) / (N - 2)) + N - 3;
                flag = -1;
                N -= 4;
            }
        }
        return ret;
    }

Also I saw an O(n) solution with the fact that for n >= 5, (n + 2) > (n * (n - 1)) / (n - 2) > (n + 1).

so we get (n * (n - 1)) / (n -2) = n + 1 here.

therefore for n = 1, result = 1

for n = 2, result = 2

for n = 3, result = 6

for n = 4, result = 7,

for n >= 5, for (n - 1) % 4 == 0, result is 5 * 4 / 3 + 2 - 1 or n * (n - 1)/ (n - 2) + … + (8 * 7 / 6) - 5 * 4/ 3 + 2 - 1 = (n + 1) + 2 - 1 = n + 2

if (n - 1) % 4 == 1, result is 6 * 5 / 4 + 3 - 2 * 1 = (n + 1) + 1 = n + 2

if (n - 1) % 4 == 2 , result = 7 * 6 / 5 + 4 - (3 * 2) = n + 1 - 2 = n -1;

if (n - 1) % 4 == 3, result = 8 * 7 / 6 + 5 - 4 * 3 / 2 + 1 = n + 1

the code is as below, although I may not spend much time figuring out the formula

class Solution {
    public int clumsy(int N) {
        int[] ret = {1, 2, 6, 7};
        if (N < 5) return ret[N - 1];
        if ((N - 1) % 4 == 0) return N + 2;
        else if ((N - 1) % 4 == 1) return N + 2;
        else if ((N - 1) % 4 == 2) return N - 1;
        else return N + 1;
    }
}

猜你喜欢

转载自www.cnblogs.com/exhausttolive/p/10527347.html