Leetcode-3287

Find the Maximum Sequence Value of Array

Time complexity: $O(nk)$

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
#include <vector>

class Solution {
public:
    int maxValue(std::vector<int>& nums, int k) {
        int A[400][128] = { 0 }, AA[201][128] = { 0 };
        int B[400][128] = { 0 }, BB[201][128] = { 0 };
        AA[0][0] = BB[0][0] = true;
        
        int n = nums.size();
        for (int i = 0; i < nums.size(); ++i) {
            for (int j = std::min(k - 1, i + 1); j >= 0; --j) {
                for (int c = 0; c < 128; ++c) {
                    if (AA[j][c]) {
                        AA[j + 1][nums[i] | c] = true;
                    }
                    if (BB[j][c]) {
                        BB[j + 1][nums[n - i - 1] | c] = true;
                    }
                }
            }
            
            for (int c = 0; c < 128; ++c) {
                if (AA[k][c]) {
                    A[i][c] = true;
                }
                if (BB[k][c]) {
                    B[i][c] = true;
                }
            }
        }
        
        int res = 0;
        for (int i = k - 1; i < n - k; ++i) {
            for (int c1 = 0; c1 < 128; ++c1) {
                if (!A[i][c1]) {
                    continue;
                }
                for (int c2 = 0; c2 < 128; ++c2) {
                    if (B[n - i - 2][c2]) {
                        res = std::max(c1 ^ c2, res);
                    }
                }
            }
        }
        
        return res;
    }
};

Leetcode-3287

Licensed under CC BY-NC-SA 4.0