题解 | #子数组的最大累加和问题#
子数组的最大累加和问题
https://www.nowcoder.com/practice/554aa508dd5d4fefbf0f86e5fe953abd
import java.util.*; public class Solution { /** * max sum of the subarray * @param arr int整型一维数组 the array * @return int整型 */ public int maxsumofSubarray (int[] arr) { // write code here if(arr.length == 0) return -1; int max = 0; int cur = 0; for(int i = 0; i< arr.length; i++){ cur += arr[i]; max = Math.max(max,cur); cur = cur < 0 ? 0 : cur; } return max; } }
cur记录当前最大值,如果cur < 0 则直接舍弃,重新赋0