Leetcode-MaximumSubarray

题目

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

A subarray is a contiguous part of an array.

  • Example 1:

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

       Input: nums = [1]
       Output: 1
    
  • Example 3:

      Input: nums = [5,4,-1,7,8]
      Output: 23
    
  • Constraints:

       1 <= nums.length <= 105
       -104 <= nums[i] <= 104
    

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.

解法

public class MaximumSubarray {
    
    public static void main(String[] args) {
        int nums[] = {-2, 1, -3, 4, -1, 2, 1, -5, 4};

//        int nums2[] = {5, 4, -1, 7, 8};

        int result = Solution.maxSubArray(nums);
        System.out.println(result);
    }

    static class Solution {

        public static int maxSubArray(int[] nums) {
            int result = nums[0];
            int sum = 0;

            for (int num : nums) {
                if (sum > 0)
                    sum += num;
                else
                    sum = num;

                result = Math.max(result, sum);
            }
            return result;
        }
    }


    class Solution2 {
        public int maxSubArray(int[] nums) {
            if (nums == null)
                return 0;
            // 遍历所有的情况中的最大和
            int ans = nums[0];
            // 当前子数组的和情况
            int sum = 0;

            /**
             *遍历数组  如果有正数  那么最大和子数组应该是以正数开头正数结尾的
             *
             *对于全都是负数的情况  那么遍历获取最大的负数就可以了
             *
             *当正数开始  并且一直相加和>0的时候  允许你中间有部分容错(即中间存在部分负数)
             *此时记录遍历的最大和情况  即 ans=Math.max(sum,ans);
             *如果和<=0了 那么代表容错没有了 加上后续的值无论后面的是正负哪种,都还不如不加
             *直接以后面的值作为新的子数组开头 继续遍历
             */

            for (int num : nums) {
                //如果和大于0  则加上遍历的数字  即使num<0也没事  允许其有部分容错
                if (sum > 0) {
                    sum += num;
                } else {
                    // 和小于0了  那么就让和等于num  就代表从该值重新开启新的连续子数组
                    sum = num;
                }
                //保存获得此时最大和
                ans = Math.max(sum, ans);
            }
            return ans;
        }
    }


}

代码地址

https://gitee.com/eistert/eistert-java-study-note/blob/master/leetcode/leetcode-programming-questions/src/main/java/com/eistert/leetcode/array/MaximumSubarray.java

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-subarray
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值