53. Maximum Subarray

本文介绍了一种寻找具有最大和的连续子数组的算法,并提供了一个示例代码实现。该算法能够有效地解决这一问题,时间复杂度为O(n),通过不断更新当前子数组的和以及记录最大和的方式找到最优解。
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.

Seen this question in a real interview before?  No
Thanks for your feedback.
Difficulty:Easy
Total Accepted:345.9K
Total Submissions:845.3K
Contributor:LeetCode
Subscribe to see which companies asked this question.

Related Topics 
ArrayDivide and ConquerDynamic Programming
Similar Questions 
Best Time to Buy and Sell StockMaximum Product SubarrayDegree of an Array
Java	


1
class Solution {
2
   
3
    public int maxSubArray(int[] nums) {
4
        int sum = nums[0];
5
        int result = nums[0];
6
        for (int i = 1; i < nums.length; i++) {
7
            if (sum < 0) {
8
                if (nums[i] > sum) {
9
                    sum = nums[i];
10
                    result = Math.max(result, nums[i]);
11
                }
12
            } else {
13
                result = Math.max(result, sum + nums[i]);
14
                sum += nums[i];
15
​
16
            }
17
        }
18
        return result;
19
​
20
    }
21
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值