• + 0 comments

    Java code

    public static List maxSubarray(List arr) { if (arr.size() == 1) { return List.of(arr.get(0), arr.get(0)); }

        if (arr.stream().allMatch(i -> i < 0)) {
            int maxNegative = arr.stream().mapToInt(Integer::intValue).max().orElse(Integer.MIN_VALUE);
            return List.of(maxNegative, maxNegative);
        }
    
        int currentValue = 0;
        int maxValue = 0;
    
        for (int i = 0; i < arr.size(); i++) {
            int value = arr.get(i);
            if (value >= 0) {
                currentValue += value;
            } else {
                if (currentValue + value > 0) {
                    currentValue += value;
                } else {
                    currentValue = Math.max(currentValue, value);
                    currentValue = 0;
                }
            }
    
            maxValue = Math.max(maxValue, currentValue);
        }
    
        return List.of(maxValue, arr.stream()
                .filter(value -> value > 0)
                .mapToInt(Integer::intValue)
                .sum());
    }