Skip to content

Latest commit

 

History

History
47 lines (37 loc) · 1.07 KB

File metadata and controls

47 lines (37 loc) · 1.07 KB

523. Continuous Subarray Sum


题目地址

https://www.jiuzhang.com/solution/continuous-subarray-sum/

题目描述

Given an integer array, find a continuous subarray where the sum of numbers is the biggest. Your code should return the index of the first number and the index of the last number. (If their are duplicate answer, return the minimum one in lexicographical order)

代码

public class Solution {
    public ArrayList<Integer> continuousSubAraySum(int[] nums) {
    ArrayList<Integer> result = new ArrayList<Integer>();
    result.add(0);
    result.add(0);

    int len = A.length;
    int start = 0, end = 0;
    int sum = 0;
    int ans = Integer.MIN_VALUE;
    for (int i = 0; i < len; i++) {
      if (sum < 0) {
        sum = nums[i];
        start = end = i;
      } else {
        sum += nums[i];
        end = i;
      } 

      if (sum > ans) {
        ans = sum;
        result.set(0, start);
        result.set(1, end);
      }

    }
    return result;
  }
}