Smallest Sum Contiguous Subarray in Java
codemania
Asked: May 27, 20232023-05-27T09:34:57+00:00
2023-05-27T09:34:57+00:00In: Education
Smallest Sum Contiguous Subarray in Java
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This is the Java Program to Find the Minimum Sum in a Contiguous Sub-Array.
Given an array of integers, find the contiguous subarray, whose sum of the elements, is minimum.
Example:
Array = [2 1 3 5 -2 1 -3 8]
Output
Subarray = [-2 1 -3]
Sum = -4
The idea is to divide the array recursively into two equal parts. Find the middle index of the array, recursively find the minimum sum subarray, in the left part and the right part, find the minimum sum crossing subarray as well,finally return the subarray having the minimum sum.
Here is the source code of the Java Program to Find the Minimum Sum in a Contiguous Sub-Array. The program is successfully compiled and tested using IDE IntelliJ Idea in Windows 7. The program output is also shown below.
//Java Program to Find the Minimum Sum in a Contiguous Sub-Array
// Function to find the crossing subarray with minimum sum
}
}
}
}
}
// Function to recursively find minimum subarray in left and right parts
}
}
// Fumction to read user input
}
}
}
}
}
}
1. In function minCrossingSubarray(), the variables lsum and rsum are initialized to Integer.MAX_VALUE.
2. The loop for(i=mid;i>=0; i–) is used to find the minimum sum subarray when moving from the middle element towards the leftmost element.
3. The loop for(i=mid+1;i<=high; i++) is used to find the minimum sum subarray when moving from the middle element towards the rightmost element.
4. Finally, the output array is updated to contain the index of the leftmost and rightmost element, upto where the sum is maximum and the maximum sum is also stored in it as (lsum + rsum).
5. In function minimumSumSubarray(), the condition if(low == high) checks if there is only element, in the array.
6. If there is only one element, then the output array is updated as required.
7. Otherwise, the index of the middle element is calculated and the function minimumSumSubarray() is recursively called on left and right halves.
8. Finally, the function minCrossingSubarray() is called and the output arrays returned from the three calls are compared. The array containing the minimum sum is returned.
Time Complexity: O(n*log(n)) where n is the number of elements in the array.