53.最大子序和Leetcode

思路一:暴力求解(O(n^3))

class Solution {
    public int maxSubArray(int[] nums) {
        
        int maxSum = 0;
        
        for(int start = 0; start < nums.length; start++){//确定子序列的起点
            for(int end = start; end < nums.length; end++){//确定子序列的终点
                int thisSum = 0;
                for(int index = start; index <= end; index++){
                    thisSum = thisSum + nums[index];
                }
                if(thisSum > maxSum){
                    maxSum = thisSum;
                }
            }
        }
        return maxSum;
    }
}

思路二:暴力求解的改进(O(n^2))

class Solution {
    public int maxSubArray(int[] nums) {
        
        int maxSum = Integer.MIN_VALUE;
        
        for(int i = 0; i < nums.length; i++){//确定子序列的起点
        int thisSum = 0;
            for(int j = i; j < nums.length; j++){//确定子序列的终点
                thisSum += nums[j];
                if(thisSum > maxSum){
                    maxSum = thisSum;
                }
            }
        }
        return maxSum;
    }
}

这里需要注意的地方:

开始要定义maxSum = Integer.MIN_VALUE

原因是数列中有负数的存在

思路三:动态规划(大事化小,小事化了)

猜你喜欢

转载自blog.csdn.net/qq_32682177/article/details/81661593