题解 | #连续子数组的最大和(二)#

连续子数组的最大和(二)

https://www.nowcoder.com/practice/11662ff51a714bbd8de809a89c481e21

import java.util.*;
import java.lang.*;

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param array int整型一维数组 
     * @return int整型一维数组
     */
    public int[] FindGreatestSumOfSubArray (int[] array) {
        // write code here
        int cur = 0;
        int max = Integer.MIN_VALUE,left = 0,right = 0;
        for(int i = 0;i < array.length;i++){
            cur += array[i];
            if(max <= cur){
                max = cur;
                right = i;
            }
            if(cur < 0){
                cur = 0;
                left = i + 1;
                
            }
        }
        int[] res;
        if(left > right){
            res = new int[]{array[right]};
        }else{
            res = new int[right-left+1];
            int j = 0;
            for(int i = left;i<=right;i++){
                res[j++] = array[i];
            }
        }
        return res;

    }
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务