zoukankan      html  css  js  c++  java
  • [Algo] 489. Largest SubArray Sum

    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};
      }
    }
  • 相关阅读:
    DFS-B
    DFS/BFS-A
    DFS-回溯与剪枝-C
    BFS-八数码问题与状态图搜索
    PTA-1003 我要通过!
    二分-G
    二分-F
    二分-E
    二分-D
    二分-C
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12602776.html
Copyright © 2011-2022 走看看