LeetCode-环形子数组的最大和

336 阅读1分钟

算法记录

LeetCode 题目:

  给定一个长度为 n 的环形整数数组 nums ,返回 nums 的非空 子数组 的最大可能和


说明

一、题目

  环形数组 意味着数组的末端将会与开头相连呈环状。形式上, nums[i] 的下一个元素是 nums[(i + 1) % n] , nums[i] 的前一个元素是 nums[(i - 1 + n) % n] 。

二、分析

  • 连续子数组的最大和一般使用单调栈和前缀和来解决,这里因为是循环的原因,因此需要构建一个二倍大小的前缀和数组。
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        return find(root, p, q);
    }

    public TreeNode find(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null) return null;
        if(root == p || root == q) return root;
        TreeNode l = find(root.left, p, q);
        TreeNode r = find(root.right, p, q);
        if(l != null && r != null) return root;
        if(l != null) return l;
        return r;
    }
}

总结

熟悉前缀和、单调栈的使用。