leetcode+Huawei written test questions-java implementation returns the sum of the largest subarray in an integer array

write picture description here

Method 1: Violent enumeration
Define a maximum value max to initialize a small number, define a variable sum to represent the sum value, traverse the array elements, start from the first element, and add them in turn, if the sum sum is greater than the maximum value max Assign sum to the maximum value. Then another loop controls the sum from the i-th array element until n.
Time complexity: O(n^2)

Method 2: Greedy method
Because each summation is to add the elements in front of i, there will be repetitions. If there is a negative number after the addition, it means that I will continue to traverse to find the first positive number. All preceding elements whose sum is negative are discarded. If no positive number is found, the current value max is the maximum value.
Time complexity: O(n)

code show as below:

public class Demo1 {
    public static void main(String[] args) {
        int arr[] = { 2, -3, 4, 11, -5, 8, 3, -6 };
        int maxSum = getMaxSum2(arr);
        System.out.println("最大子数组的和为:" + maxSum);
    }

    private static int getMaxSum(int[] arr) {
        int max = -100000;
        for (int i = 0; i < arr.length; i++) {
            int sum = 0;
            for (int j = i; j < arr.length; j++) {
                sum += arr[j];
                if (max < sum) {
                    max = sum;
                }
            }
        }

        return max;
    }

    // 贪心法
    private static int getMaxSum2(int[] arr) {
        int n = arr.length;
        int max = -1000000;
        int sum = 0;
        for (int i = 0; i < n; i++) {
            sum += arr[i];
            if (sum > max) {
                max = sum;
            }
            if (sum < 0) {
                max = 0; // 子串和为负数,丢掉
            }
        }
        return max;
    }

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326225601&siteId=291194637