Given an integer array nums, please find a contiguous subarray with the largest sum (the subarray contains at least one element), and return its largest sum. A subarray is a contiguous part of an array. 【LeetCode Hot 100】

Question 53 of the Hottest Questions 100:

Paste the code first:

class Solution {
    public int maxSubArray(int[] nums) {
        //定义一个cur,存储子数组的和
        int cur = 0;
        //定义maxsum,为连续子数组的最大和
        int maxsum = nums[0];
        //for循环遍历数组,cur为从0开始的子数组和,若遍历到x时,之前子数组的和小于x的值
        //则抛弃之前的子数组,cur从当前的x开始计算新的子数组的和
        //maxsum记录每一个子数组之间的最大值!
        for (int x : nums) {
            cur = Math.max(cur + x, x);
            maxsum = Math.max(maxsum, cur);
        }
        //返回maxsum
        return maxsum;
    }
}

Problem- solving ideas : In this question, we are required to find the maximum sum of consecutive sub-arrays. It should be noted that the sub-arrays must be continuous, that is, the subscripts increase continuously. However, the title does not require the specific size of the sub-array. It may be one element or three elements. We do not know. The simplest and most intuitive method is to list all sub-arrays when the element is 1. When the element is 2 for all subarrays, and so on, and finally find the maximum value of the sum between these subarrays. But it is too cumbersome to write in this way, and the time complexity is also very high, so can we optimize it further?

The method we just mentioned is to list all the subarrays and find the largest sum in these subarrays. Then we can define a variable cur to represent the sum of a current subarray. cur starts from 0 and adds the value of the elements in turn. If the sum of the subarray and cur plus the value of the i subscript is less than the value of the i subscript when traversing to i, then let cur start from the i subscript Calculate the sum of the new subarray, because the sum of the previous consecutive elements is already less than the value of the first element of the new subarray.

This can solve the problem in one traversal.

Guess you like

Origin blog.csdn.net/weixin_56960711/article/details/123280785