classSolution { publicintmaxSubArray(int[] nums) {int res = nums[0];int sum = nums[0];for (int i =1; i <nums.length; i++) {// 自身最大 or 自身包含之前的 sum 的最大 sum =Math.max(nums[i], sum + nums[i]); res =Math.max(res, sum); }return res; }}
can be also wrote like this
classSolution {publicintmaxSubArray(int[] nums) {int max = nums[0];int presum = nums[0];for (int i =1; i <nums.length; i++) { presum =Math.max(0, presum) + nums[i]; max =Math.max(max, presum); }return max; }}