tromu
tromu

Reputation: 35

Numbers which constitute the Maximum sum

I just wrote my program which finds the maximum sum from the array, but I am stuck in is there any way by which I can find which numbers contributed to the max sum?

Rule of Maximum sum is given: No adjacent elements should contribute to sum.

My solution to maximum sum in array:

public class MaximumELementInARray {
    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        String[] al = reader.nextLine().split(" ");
        int[] input = Arrays.stream(al).mapToInt(Integer::parseInt).toArray();
        MaximumELementInARray mm = new MaximumELementInARray();
        int maxi = mm.maximumm(input);
        System.out.println(maxi);
    }

    public int maximumm(int[] a) {
        List<Integer> ex = new ArrayList<>();
        List<Integer> inc = new ArrayList<>();
        int incl = a[0];
        int excl = 0;
        int excl_new;
        for (int i = 1; i < a.length; i++) {
            excl_new = Math.max(incl, excl);
            incl = excl + a[i];
            excl = excl_new;
        }
        System.out.println(incl > excl ? inc : ex);
        return incl > excl ? incl : excl;
    }
}

Now in the maximum function is there a tweak where I can put all the index of elements which constituted to the maximum sum?

Input:

-1 7 8 -5 4 9 -2 3

Output:

20

**

I require how 20 was arrived at. The answer should say 8+9+3

**

I believe that in maximum function we could put an Arraylist and record which which elements are contributing to sum, but I am not able to implement.

I have made two Arraylist :

List<Integer> ex = new ArrayList<>();
List<Integer> inc = new ArrayList<>();

Input: -1 7 8 -5 4 Output: 12 The Sum is made up of 8+4


Input: 3 2 1 -1 Output: 4 The sum is made up of 3+1

etc....

Upvotes: 3

Views: 885

Answers (1)

Hadi
Hadi

Reputation: 17289

You can follow this code.

    int toIndex = 3, fromIndex = 0;
    List<Integer> result = new ArrayList<>();
    while (toIndex < numbers.size()) {
        Map<Integer, Integer> map = IntStream
                .range(fromIndex, toIndex)
                .filter(i->numbers.get(i)>0)
                .mapToObj(i -> new AbstractMap.SimpleEntry<>(i, numbers.get(i)))
                .collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey,(a,b)->b));
        // find max of sublist
        int maxOfSub = numbers.subList(fromIndex, toIndex).stream().max(Integer::compareTo).get();
        //update indexes
        fromIndex = map.getOrDefault(maxOfSub,toIndex-1) + 2;
        toIndex += fromIndex;

        if (maxOfSub > 0)
            result.add(maxOfSub);
    }
    int lastMax = numbers.subList(fromIndex, numbers.size()).stream().max(Integer::compareTo).get();
    if (lastMax > 0)
        result.add(lastMax);
    System.out.println(result);
    System.out.println(result.stream().reduce(0, Integer::sum));

DEMO

Upvotes: 3

Related Questions