Dashboard Temp Share Shortlinks Frames API

HTMLify

Max Xor Subarray of size K
Views: 4 | Author: prakhardoneria
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution:
    def maxSubarrayXOR(self, arr, k):
        n = len(arr)
        current_xor = 0
        
        # 1. Calculate the XOR of the first window of size k
        for i in range(k):
            current_xor ^= arr[i]
            
        max_xor = current_xor
        
        # 2. Slide the window across the rest of the array
        for i in range(k, n):
            # XOR out the element leaving the window and XOR in the new element
            current_xor = (current_xor ^ arr[i-k]) ^ arr[i]
            
            # Update max_xor if the current window's XOR is higher
            if current_xor > max_xor:
                max_xor = current_xor
                
        return max_xor