Niuke.com Brushing Questions-The maximum cumulative sum of sub-arrays

Problem Description

Given an array arr, return the maximum cumulative sum of the sub-array (the title guarantees that there is no data with all negative numbers)
For example, arr = [1, -2, 3, 5, -2, 6, -1], in all sub-arrays , [3, 5, -2, 6] can accumulate the largest sum of 12, so it returns 12.

Example

Example 1

Enter
[1, -2, 3, 5, -2, 6, -1]

Output
12

Solutions

Ideas

  1. Brute force solution: nested traversal
  2. Dynamic programming: traverse the array and accumulate the sum. When it is found that the sum is less than 0, it means that the previous element has the largest element. We need to start the sum from 0 again and repeat the above process.

Code

// 思路1
public class Solution {
    
      
    public int maxsumofSubarray(int[] arr) {
    
    
        int max = Integer.MIN_VALUE;
        int res = 0;
        for (int i = 0; i < arr.length; i++) {
    
    
            res = Math.max(res + arr[i], 0);
            max = Math.max(max, res);
        }
        return max;
    }
}

Time complexity analysis:
O(N): Traverse the array

Space complexity analysis:
O(1): No extra space is used

If you want to test, you can go directly to the link of Niuke.com to do the test

The problem of the maximum cumulative sum of sub-arrays

Guess you like

Origin blog.csdn.net/qq_35398517/article/details/114049097