LintCode 722: Maximum Subarray VI (Trie, 异或经典难题)

本文介绍了一种使用Trie树和XOR操作求解最大子数组XOR值的高效算法。通过构建前缀XOR数组和Trie树,算法能在O(n)时间内找到给定数组中具有最大XOR值的子数组。

722. Maximum Subarray VI

Given an array of integers. find the maximum XOR subarray value in given array.

What's the XOR: https://en.wikipedia.org/wiki/Exclusive_or

Example

Example 1

Input: [1, 2, 3, 4]
Output: 7
Explanation:
The subarray [3, 4] has maximum XOR value

Example 2

Input: [8, 1, 2, 12, 7, 6]
Output: 15
Explanation:
The subarray [1, 2, 12] has maximum XOR value

Example 3

Input: [4, 6]
Output: 6
Explanation:
The subarray [6] has maximum XOR value

Notice

Expected time complexity O(n).

Input test data (one parameter per line)How to understand a testcase?

 

 

解法1:Trie+XOR。

用Trie和异或的解法我感觉非常难,看答案也是看了很久才看明白。下面这两个链接讲得非常不错。

https://www.geeksforgeeks.org/find-the-maximum-subarray-xor-in-a-given-array/

https://lengerrong.blogspot.com/2017/11/maximum-subarray-vi.html

首先,我们感觉好像用XOR的话,就不能有presum这样的数组了,但是实际上是可以有的,因为XOR有下面的特性:

prexor(L,R) = prexor(1,R) ^ prexor(1,L-1), prexor(L,R) is XOR of subarray from L to R。所以我们可以建立类似的prexor数组,即prexor[i]=F(1, i)。

另外,为什么要用Trie呢?这样就可以节省时间了,可以在O(n)的时间内找出前面的数字的prexor。

 

以输入A[]= {8, 2, 1, 12}为例。为简便起见,假设A数组从1开始,假定prexor[0] = 0。易知prexor[1] = 8 (1010),prexor[2]= 10 (1010), prexor[3] = 11 (1011)。

每来一个A[i],我们将prexor[i]插入trie树中。下图是A[3]=1来后的情形。注意,每次插入A[i]后我们还要调用query()函数返回当前能找到的最大的那个XOR值。那么这个最大的XOR值怎么找呢?利用prexor(L,R) = prexor(1,R) ^ prexor(1,L-1)。我们已经知道prexor(1,R),那么,我们只要在trie树上找到之前能和prexor(1,R)异或出最大结果的那个prexor(1,L-1)即可。因为在trie树上已经存了所有prexor(1,i), i=1,...,R-1的值。我们的任务就是要在prexor[1,...,R-1]中找到一个最优的数prexor[X], 使得prexor(1,R)^prexor(1,X)最大,这里的X就是L-1,那么这个最大值就是题目所求的最大XOR subarray的值。

 

下图是A[4]=12来后的情形。prexor=7(0b0111)已经插入trie中,我们要在trie中找到一个最优的prexor[i],使得其与0b0111异或出来最大。注意prexor[i]的值都存在叶子节点中。我们可以看到找到的最优的prexor[i]是prexor[1]=8(0b1000),而这个最大值就是7 XOR 8 = 15 (0b1111), 因为X=1,这个subarray就是A[2..4],注意2=X+1。

怎么找最大的prexor[i]的关键在于query里面的算法:

        // Find current bit in given prefix 
        bool val = pre_xor & (1 << i); 
  
        // Traverse Trie, first look for a 
        // prefix that has opposite bit 
        if (temp->arr[1 - val] != NULL) 
            temp = temp->arr[1 - val]; 
  
        // If there is no prefix with opposite 
        // bit, then look for same bit. 
        else if (temp->arr[val] != NULL) 
            temp = temp->arr[val]; 

从高到低遍历bit,每次先找跟prexor的对应bit相反的bit,找不到才找相同的bit。为什么先找相反的bit呢?就是为了让XOR值最大嘛!

代码如下:

 

#define INT_SIZE 32 

struct TrieNode 
{ 
    int value;  // Only used in leaf nodes 
    TrieNode *arr[2]; 
}; 
  
// create a Trie node 
TrieNode *newNode() 
{ 
    TrieNode *temp = new TrieNode; 
    temp->value = 0; 
    temp->arr[0] = temp->arr[1] = NULL; 
    return temp; 
} 
  
// Inserts pre_xor to trie with given root 
void insert(TrieNode *root, int pre_xor) 
{ 
    TrieNode *temp = root; 
  
    // Start from the msb, insert all bits of 
    // pre_xor into Trie 
    for (int i = INT_SIZE - 1; i >= 0; i--) 
    { 
        // Find current bit in given prefix 
        bool val = pre_xor & (1 << i); 
  
        // Create a new node if needed 
        if (temp->arr[val] == NULL) 
            temp->arr[val] = newNode(); 
  
        temp = temp->arr[val]; 
    } 
  
    // Store value at leaf node 
    temp->value = pre_xor; 
} 
  
// Finds the maximum XOR ending with last number in 
// prefix XOR 'pre_xor' and returns the XOR of this maximum 
// with pre_xor which is maximum XOR ending with last element 
// of pre_xor. 
int query(TrieNode *root, int pre_xor) 
{ 
    TrieNode *temp = root; 
    for (int i = INT_SIZE-1; i >= 0; i--) 
    { 
        // Find current bit in given prefix 
        bool val = pre_xor & (1 << i); 
  
        // Traverse Trie, first look for a 
        // prefix that has opposite bit 
        if (temp->arr[1 - val] != NULL) 
            temp = temp->arr[1 - val]; 
  
        // If there is no prefix with opposite 
        // bit, then look for same bit. 
        else if (temp->arr[val] != NULL) 
            temp = temp->arr[val]; 
    } 
    return pre_xor ^ (temp->value); 
} 

class Solution {
public:
    /**
     * @param nums: the array
     * @return: the max xor sum of the subarray in a given array
     */
    int maxXorSubarray(vector<int> &nums) {
        TrieNode *root = newNode(); 
        insert(root, 0); 
        int n = nums.size();
        // Initialize answer and xor of current prefix 
        int result = INT_MIN, pre_xor = 0; 
      
        // Traverse all input array element 
        for (int i = 0; i < n; i++) 
        { 
            
            // update current prefix xor and insert it into Trie 
            pre_xor = pre_xor ^ nums[i]; 
            insert(root, pre_xor); 
      
            // Query for current prefix xor in Trie and update 
            // result if required 
            result = max(result, query(root, pre_xor)); 

        } 
        return result; 
    }
};

 

 

### 最大子数组和算法实现与解释 最大子数组和问题旨在从一个整数数组中找出具有最大和的连续子数组。该问题的经典解法采用动态规划思想,其核心逻辑在于逐个位置计算以当前元素结尾的最大子数组和,并记录全局最大值。 动态规划状态转移方程如下: `maxSubArray(A, i) = maxSubArray(A, i - 1) > 0 ? maxSubArray(A, i - 1) : 0 + A[i]` 该公式表示如果前一个位置的最大子数组和大于零,则将其加入当前位置的数值形成新的候选值;否则仅保留当前位置的数值作为起始点。通过这种方式,可以在线性时间内完成整个数组的遍历并求出最大子数组和[^1]。 #### Java 实现示例 ```java class Solution { public int maxSubArray(int[] A) { int n = A.length; int[] dp = new int[n]; // dp[i] 表示以 A[i] 结尾的最大子数组和 dp[0] = A[0]; int max = dp[0]; for (int i = 1; i < n; i++) { dp[i] = A[i] + (dp[i - 1] > 0 ? dp[i - 1] : 0); max = Math.max(max, dp[i]); } return max; } } ``` 上述代码使用了一个长度为 `n` 的数组 `dp` 来存储每个位置上的最大子数组和,最终返回全局最大值 `max`。该方法的时间复杂度为 O(n),空间复杂度也为 O(n)。 为了进一步优化空间复杂度,可以仅维护前一个状态的值,从而将空间复杂度降低至 O(1): #### 空间优化版本(O(1)) ```java class Solution { public int maxSubArray(int[] nums) { if (nums == null || nums.length == 0) { return 0; } int prev = nums[0]; int result = prev; for (int i = 1; i < nums.length; ++i) { prev = Math.max(nums[i], prev + nums[i]); result = Math.max(result, prev); } return result; } } ``` 在该实现中,变量 `prev` 记录以当前元素结尾的最大子数组和,而 `result` 跟踪整个过程中的最大值。这样避免了额外数组的使用,使空间效率更优[^2]。 --- ### 相关应用场景 该算法不仅适用于最大子数组问题本身,还可推广至股票买卖利润最大化等场景。例如,在给定每日股价数组中寻找最大收益时,可以通过构造价格差分数组并应用最大子数组和算法来解决[^3]。 --- ### 示例:C++ 实现(异常安全与空间优化) 以下是一个 C++ 版本的实现,结合了内存管理优化和异常处理机制,确保程序在面对大规模输入时具备更好的鲁棒性: ```cpp #include <iostream> #include <vector> #include <algorithm> int maxSubArraySum(const std::vector<int>& nums) { if (nums.empty()) return 0; int prev = nums[0]; int result = prev; for (size_t i = 1; i < nums.size(); ++i) { prev = std::max(nums[i], prev + nums[i]); result = std::max(result, prev); } return result; } int main() { try { std::vector<int> nums; nums.reserve(1 << 20); // 预留百万级元素的空间 for (int i = 0; i < 1000000; ++i) { nums.push_back(i % 100 - 50); // [-50, 49] } int maxSum = maxSubArraySum(nums); std::cout << "Maximum subarray sum: " << maxSum << std::endl; } catch (const std::bad_alloc& e) { std::cerr << "Memory allocation failed: " << e.what() << std::endl; } catch (...) { std::cerr << "An unexpected error occurred." << std::endl; } return 0; } ``` 此实现通过 `reserve()` 提前分配足够容量,减少频繁扩容带来的性能开销,并通过 `try-catch` 捕获可能的内存分配异常,提高程序稳定性[^1]。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值