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};
      }
    }
  • 相关阅读:
    关于pipe管道的读写端关闭问题
    线性表的链式存储——C语言实现
    关于无法解析的外部符号 _main
    Tomcat域名与服务器多对多配置
    JavaScript基础
    Vue.js入门
    SpringBoot注解大全,收藏一波!!!
    数据库连接错误
    SpringBoot入门
    MyBatis插入并返回id技巧
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12602776.html
Copyright © 2011-2022 走看看