[Algo] 489. Largest SubArray Sum

ⅰ亾dé卋堺 提交于 2020-03-31 08:14:32

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};
  }
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!