Maximum Subarray Sum

  • + 0 comments

    pure java... package geeksforgeeks; import java.util.*;

    public class Maxnumber {

    public static void main(String[] args) {
        int module, sum = 0, maxNumber = 0, start = 0, repeat = 2, sumofarray = 0, decrese = 1;
        Scanner sc = new Scanner(System.in);
    
        System.out.println("size");
        int n = sc.nextInt();
        int arr[] = new int[n];
    
        System.out.println("element");
        for (int i = 0; i < n; i++) {
            arr[i] = sc.nextInt();
        }
    
        System.out.println("modulo");
        module = sc.nextInt();
    
        // Sum of the whole array
        for (int i = 0; i < arr.length; i++) {
            sum += arr[i];
        }
    
        int remainder = sum % module;
        maxNumber = Math.max(remainder, maxNumber);
    
        // Check subarrays with different lengths
        while (start != arr.length - 1) {
            int x = 0;
            int index = start;  // Start index for each iteration
    
            while (x != repeat && index < arr.length) {  // Prevent out of bounds
                for (int j = 0; j < decrese && index < arr.length; j++) {
                    sumofarray += arr[index];
                    index++;
                }
                remainder = (sum - sumofarray) % module;
                maxNumber = Math.max(remainder, maxNumber);
                sumofarray = 0;  // Reset sum for the next subarray
                x++;
            }
            start++;
            repeat++;
            decrese++;
        }
    
        System.out.println(maxNumber);
        sc.close();
    }
    

    }