codewas057: 最大和子數組

Instructions:

Maximum subarray sumhtml

Solution:

public class Max{
    public static int sequence(int[] arr){
        if(arr == null || arr.length == 0){
            return 0;
        }    
        Boolean negative = true;
        for(int x : arr){
            if(x > 0){
                negative = false;
                break;
            }    
        }    
        if(negative){
            return 0;
        }    
        int max = arr[0];
        int sum = 0;
        for(int i = 0; i < arr.length; i++){
            if(sum <= 0){
                sum = arr[i];
            }else{
                sum += arr[i];
            }    
            if(sum > max){
                max = sum;
            }                   
        }    
        return max;
    }            
}

Example Test:

TBD
https://www.codewars.com/kata/54521e9ec8e60bc4de000d6c/train/java

Reference

相關文章
相關標籤/搜索