• LeetCode


    题目:

    Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

    For example, given the array [−2,1,−3,4,−1,2,1,−5,4],
    the contiguous subarray [4,−1,2,1] has the largest sum = 6.

    思路:

    保存两个值max和leftSum,max就是到目前为止所能得到的最大值,leftSum为包含当前元素的最大子串之和。然后从左往右扫,下面的代码的if else语句把各种情况都摆明了。

    package array;
    
    public class MaximumSubarray {
    
        public int maxSubArray(int[] nums) {
            int n;
            if (nums == null || (n = nums.length) == 0) return 0;
            int max = nums[0];
            int leftSum = nums[0];
            for (int i = 1; i < n; ++i) {
                if (nums[i] >= 0) {
                    if (leftSum >= 0) {
                        leftSum += nums[i];                    
                    } else {
                        leftSum = nums[i];
                    }
                    
                    if (max < leftSum)
                        max = leftSum;
                } else {
                    if (leftSum + nums[i] >= 0) {
                        leftSum += nums[i];
                    } else {
                        leftSum = nums[i];
                    }
                    
                    if (max < leftSum)
                        max = leftSum;
                }
            }
            
            return max;
        }
        
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            int[] nums = { /*-2,1,-3,4,-1,2,1,-5,4*/ -2, -1 };
            MaximumSubarray m = new MaximumSubarray();
            System.out.println(m.maxSubArray(nums));
        }
    
    }

    这个代码可以合并,如下:

    package array;
    
    public class MaximumSubarray {
    
        public int maxSubArray(int[] nums) {
            int n;
            if (nums == null || (n = nums.length) == 0) return 0;
            int max = nums[0];
            int leftSum = nums[0];
            for (int i = 1; i < n; ++i) {
                if (leftSum >= 0 && leftSum + nums[i] >= 0) {
                    leftSum += nums[i];
                } else {
                    leftSum = nums[i];
                }
                
                if (max < leftSum)
                    max = leftSum;
            }
            
            return max;
        }
        
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            int[] nums = { -2, -1 };
            MaximumSubarray m = new MaximumSubarray();
            System.out.println(m.maxSubArray(nums));
        }
    
    }
  • 相关阅读:
    C# Server.Transfer传值方式
    asp.net验证码生成
    pop协议指令
    Url Rewriting后的问题
    c# 一个通过oledb读取excel,csv的类
    jquery选择器全解
    覆盖与重载(override/overload) [C#]
    ASP.NET内置对象
    web开发敏捷之道应用rails进行敏捷web开发【读书笔记2】
    win7自动壁纸切换小工具AutoDesk一:初始化托盘
  • 原文地址:https://www.cnblogs.com/null00/p/5079489.html
Copyright © 2020-2023  润新知