剑指offer(牛客网)连续子数组的最大和

it2025-03-22  18

例如:{6,-3,-2,7,-15,1,2,2},连续子向量的最大和为8(从第0个开始,到第3个为止)。 给一个数组,返回它的最大连续子序列的和(子向量的长度至少是1) public class Solution { public int FindGreatestSumOfSubArray(int[] array) { int res = Integer.MIN_VALUE; //用 s 表示 当前数 前面数的最大和 int s = 0; for(int x : array) { if(s < 0) { s = 0; } s += x; res = Integer.max(res, s); } return res; } }

 

最新回复(0)