LeetCode-53.Maximum Subarray

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

Example:

Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.

Follow up:If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

1
2
3
4
5
6
7
8
9
public int maxSubArray(int[] nums) {//动规 my
        int re =nums[0];
        int curr = nums[0];
        for (int i = 1; i < nums.length; i++) {
            curr = curr<0?nums[i]:(nums[i]+curr);
            re = curr>re?curr:re;
        }
        return re;
    }  

 

分治 

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
51
52
53
public class Solution
{
    public int maxSubArray(int[] nums)
    {
        // Solution 3: Divide and Conquer. O(nlogn)
        if(nums == null || nums.length == 0)
            return 0;
         
         
        return Max_Subarray_Sum(nums, 0, nums.length-1);
    }
     
    public int Max_Subarray_Sum(int[] nums, int left, int right)
    {
        if(left == right)    // base case: meaning there is only one element.
            return nums[left];
         
        int middle = (left + right) / 2;    // calculate the middle one.
         
        // recursively call Max_Subarray_Sum to go down to base case.
        int left_mss = Max_Subarray_Sum(nums, left, middle);   
        int right_mss = Max_Subarray_Sum(nums, middle+1, right);
         
        // set up leftSum, rightSum and sum.
        int leftSum = Integer.MIN_VALUE;
        int rightSum = Integer.MIN_VALUE;
        int sum = 0;
         
        // calculate the maximum subarray sum for right half part.
        for(int i=middle+1; i<= right; i++)
        {
            sum += nums[i];
            rightSum = Integer.max(rightSum, sum);
        }
         
        sum = 0;    // reset the sum to 0.
         
        // calculate the maximum subarray sum for left half part.
        for(int i=middle; i>= left; i--)
        {
            sum += nums[i];
            leftSum = Integer.max(leftSum, sum);
        }
         
        // choose the max between left and right from down level.
        int res = Integer.max(left_mss, right_mss);
        // choose the max between res and middle range.
         
        return Integer.max(res, leftSum + rightSum);
         
    }
     
}

  

 

posted @   月半榨菜  阅读(118)  评论(0编辑  收藏  举报
编辑推荐:
· 深入理解 Mybatis 分库分表执行原理
· 如何打造一个高并发系统?
· .NET Core GC压缩(compact_phase)底层原理浅谈
· 现代计算机视觉入门之:什么是图片特征编码
· .NET 9 new features-C#13新的锁类型和语义
阅读排行:
· Spring AI + Ollama 实现 deepseek-r1 的API服务和调用
· 《HelloGitHub》第 106 期
· 数据库服务器 SQL Server 版本升级公告
· 深入理解Mybatis分库分表执行原理
· 使用 Dify + LLM 构建精确任务处理应用
点击右上角即可分享
微信分享提示