• + 0 comments

    `Java: Simple Code for Beginner:

    public static List maxSubarray(List arr) {

    int maxContiguous = Integer.MIN_VALUE;
    int currSum = 0;
    
     int maxNonContiguous = Integer.MIN_VALUE;
     int nonContiguousSum = 0;
     boolean hasPositive = false;
    
     for (int num : arr) {
    
         // Contiguous (Kadane’s algo): subarray
         currSum = Math.max(num, currSum + num);
         maxContiguous = Math.max(maxContiguous, currSum);
    
         // Non-contiguous: subsequence
         if (num > 0) {
    
             nonContiguousSum += num;
             hasPositive = true;
         }
    
         maxNonContiguous = Math.max(maxNonContiguous, num); // track max Element when all are negatives in list
     }
    
     if (!hasPositive) {
    
         nonContiguousSum = maxNonContiguous; // in case all are negative
     }
    
     List<Integer> result = new ArrayList<>();
     result.add(maxContiguous);
     result.add(nonContiguousSum);
     return result; 
    

    } `