Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,900 questions

51,831 answers

573 users

How to find contiguous subarray with the largest sum in Java

1 Answer

0 votes
import java.util.Arrays;

public class MyClass {
    public static int[] max_subarray(int[] arr) {
        if (arr.length <= 1) {
            return arr;
        }
 
        int maximum_sum_of_subarray = Integer.MIN_VALUE;
        int maximum_sum_at_current_index = 0;
        int start = 0, end = 0;
        int star_index_of_positive_sum_sequence = 0;
 
        for (int i = 0; i < arr.length; i++) {
            maximum_sum_at_current_index += arr[i];
 
            if (maximum_sum_at_current_index < arr[i]) {
                maximum_sum_at_current_index = arr[i];
                star_index_of_positive_sum_sequence = i;
            }
 
            if (maximum_sum_of_subarray < maximum_sum_at_current_index) {
                maximum_sum_of_subarray = maximum_sum_at_current_index;
                start = star_index_of_positive_sum_sequence;
                end = i;
            }
        }
 
        return Arrays.copyOfRange(arr, start, end + 1);
    }
    public static void main(String args[]) {
        int arr[] = { -3, 2, -4, 3, 5, -2, 4, 3, -6, 5 }; //  3 + 5 + -2 + 4 + 3 = 13
 
        int subarray[] = max_subarray(arr);
        
        System.out.print(Arrays.toString(subarray));
    }
}



/*
run:

[3, 5, -2, 4, 3]

*/

 



answered Jul 2, 2022 by avibootz
...