class Solution { public int maxValue(int[] nums, int k) { if (k == 1) { int rst = 0; for (int i = 0; i < nums.length; i++) { for (int j = i + 1; j < nums.length; j++) { rst = Math.max(rst, nums[i] ^ nums[j]); } } return rst; } int maxOr = 0; for (int num : nums) { maxOr = maxOr | num; } int maxSize = maxOr + 1;
int[] maxLength = new int[maxSize]; int[] minLength = new int[maxSize]; Arrays.fill(minLength, maxSize);
int[] maxLengthBuffer = new int[maxSize]; int[] minLengthBuffer = new int[maxSize];
int orCurrent; int[] kMinPos = new int[maxSize]; Arrays.fill(kMinPos, nums.length);
for (int i = 0, len = nums.length - k; i < len; i++) { System.arraycopy(maxLength, 0, maxLengthBuffer, 0, maxSize); System.arraycopy(minLength, 0, minLengthBuffer, 0, maxSize); for (int orBefore = 0; orBefore < maxLength.length; orBefore++) { if (minLength[orBefore] < k) { orCurrent = orBefore | nums[i]; if (maxLength[orCurrent] == 0) { minLengthBuffer[orCurrent] = Math.min(minLengthBuffer[orCurrent], minLength[orBefore] + 1); } maxLengthBuffer[orCurrent] = Math.max(maxLengthBuffer[orCurrent], maxLength[orBefore] + 1); if (maxLengthBuffer[orCurrent] >= k) { kMinPos[orCurrent] = Math.min(kMinPos[orCurrent], i); } } } maxLengthBuffer[nums[i]] = Math.max(1, maxLengthBuffer[nums[i]]); minLengthBuffer[nums[i]] = 1; System.arraycopy(maxLengthBuffer, 0, maxLength, 0, maxSize); System.arraycopy(minLengthBuffer, 0, minLength, 0, maxSize); } int rst = 0; Arrays.fill(maxLength, 0); Arrays.fill(minLength, maxSize); Set<Integer> visit = new HashSet<>(); for (int i = nums.length - 1; i >= k; i--) { System.arraycopy(maxLength, 0, maxLengthBuffer, 0, maxSize); System.arraycopy(minLength, 0, minLengthBuffer, 0, maxSize); for (int orBefore = 0; orBefore < maxLength.length; orBefore++) { if (minLength[orBefore] < k) { orCurrent = orBefore | nums[i]; if (maxLength[orCurrent] == 0) { minLengthBuffer[orCurrent] = Math.min(minLengthBuffer[orCurrent], minLength[orBefore] + 1); } maxLengthBuffer[orCurrent] = Math.max(maxLengthBuffer[orCurrent], maxLength[orBefore] + 1); if (maxLengthBuffer[orCurrent] >= k && !visit.contains(orCurrent)) { visit.add(orCurrent); for (int orLeft = 0; orLeft < kMinPos.length; orLeft++) { if (kMinPos[orLeft] < i) { rst = Math.max(rst, orLeft ^ orCurrent); } }
} } } maxLengthBuffer[nums[i]] = Math.max(1, maxLengthBuffer[nums[i]]); minLengthBuffer[nums[i]] = 1; System.arraycopy(maxLengthBuffer, 0, maxLength, 0, maxSize); System.arraycopy(minLengthBuffer, 0, minLength, 0, maxSize); } return rst; } }
作者:白衣生雪 链接:https: 来源:力扣(LeetCode)
|