Given an unsorted integer array, find the subarray that has the greatest sum. Return the sum and the indices of the left and right boundaries of the subarray. If there are multiple solutions, return the leftmost subarray.
Assumptions
- The given array is not null and has length of at least 1.
Examples
-
{2, -1, 4, -2, 1}, the largest subarray sum is 2 + (-1) + 4 = 5. The indices of the left and right boundaries are 0 and 2, respectively.
- {-2, -1, -3}, the largest subarray sum is -1. The indices of the left and right boundaries are both 1
Return the result in a array as [sum, left, right]
public class Solution { public int[] largestSum(int[] array) { // Write your solution here if (array == null || array.length == 0) { return array; } int globalMax = Integer.MIN_VALUE, globalLeft = 0, globalRight = 0; int left = 0; int[] sum = new int[array.length]; for (int i = 0; i < array.length; i++) { if (i == 0 || sum[i - 1] <= 0) { sum[i] = array[i]; left = i; } else { sum[i] = sum[i - 1] + array[i]; } if (sum[i] > globalMax) { globalMax = sum[i]; globalLeft = left; globalRight = i; } } return new int[]{globalMax, globalLeft, globalRight}; } }
来源:https://www.cnblogs.com/xuanlu/p/12602776.html