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};
      }
    }
  • 相关阅读:
    二维数组中的查找
    循环语句
    掷骰子游戏和条件语句
    类型转换与键盘输入
    运算符(2)
    运算符(1)
    面向对象(2)
    面向对象(1)
    理解几种排序方法
    优盘、移动硬盘简便制作启动盘
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12602776.html
Copyright © 2011-2022 走看看