Share the joy
Problem: For any given input of numbers, find the maximum sum in a range (x, y| x<=y), the sum is defined as (A[i]+ A[i+1] + … + A[j]) where x<=i<=j<=y.
This problem can be solved by greedy algotithm:
- public class LargestSequence {
- public static void main(String[] args) {
- int[] arr = { -3, -4, 3, 2, 5, -6, 3, 5, 1, -3, -2, -90, 10 };
- Interval result = findLargestSequence(arr);
- System.out.println(result);
- }
- /*
- * For any given input of numbers, find the maximum sum in a range (x, y| x<=y),
- * the sum is defined as (A[i]+ A[i+1] + … + A[j]) where x<=i<=j<=y.
- * @param the input array. element in array can be either posivie or negative.
- */
- public static Interval findLargestSequence(int[] arr) {
- if (arr == null || arr.length == 0) {
- return null;
- }
- Interval curr_interval = new Interval(0, 0);
- Interval max_interval = new Interval(0, 0);
- int max_sum = arr[0];
- int curr_sum = arr[0];
- for (int i = 1; i < arr.length; i++) {
- curr_sum += arr[i];
- curr_interval.y = i;
- if (curr_sum > max_sum) {
- max_sum = curr_sum;
- max_interval.x = curr_interval.x;
- max_interval.y = curr_interval.y;
- }
- if (curr_sum < 0) {
- curr_interval.x = i + 1;
- curr_sum = 0;
- }
- }
- return max_interval;
- }
- static class Interval {
- int x;
- int y;
- int max_sum;
- Interval(int x, int y) {
- this.x = x;
- this.y = y;
- }
- @Override
- public String toString() {
- return “(” + this.x + “, ” + this.y + “)”;
- }
- }
- }