Home > database >  How to print the longest continuous sequence whose sum of elements is maximum?
How to print the longest continuous sequence whose sum of elements is maximum?

Time:11-27

I have a code that outputs a subsequence with the maximum sum, but there is a condition "if there are 2 or more sequences equal in sum, then output the longest of them" (everything needs to be done using a list). I do not understand how to display the one that is longer.In this code the output should be 100 90 8. (the code remembers the very first of these sequences)

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    List<Integer> list = new ArrayList<>();
    list.add(1);
    list.add(2);
    list.add(-5);
    list.add(6);
    list.add(-3);
    list.add(-13434);
    list.add(99);
    list.add(99);
    list.add(-444);
    list.add(-7444);
    list.add(100);
    list.add(90);
    list.add(8);
    if (list == null || list.size() == 0) {//проверка на пустоту листа
        System.out.println("empty array");
        return;
    }

    int maxSumStartIndex = 0;
    int maxSumLastIndex = 0;
    int maxSum = list.get(0);

    int lastSumStartIndex = 0;
    int lastSum = list.get(0);

    for (int i = 1; i < list.size(); i  ) {

        lastSum  = list.get(i);
        if (lastSum < list.get(i)) {
            lastSum = list.get(i);
            lastSumStartIndex = i;
        }

        if (maxSum < lastSum) {
            maxSumStartIndex = lastSumStartIndex;
            maxSumLastIndex = i;
            maxSum = lastSum;
        }
    }

    System.out.println("sum( arr["   maxSumStartIndex   "] .. arr["   maxSumLastIndex   "] ) = "   maxSum);
    for (int i = maxSumStartIndex; i <= maxSumLastIndex; i  ) {
        System.out.print(list.get(i)   " ");
    }
}

}

CodePudding user response:

This works but don't know if its the best approach

    int maxSumStartIndex = 0;
    int maxSumLastIndex = 0;
    int maxSum = list.get(0);
    int maxSumLength = 0;

    int lastSumStartIndex = 0;
    int lastSum = list.get(0);

    for (int i = 1; i < list.size(); i  ) {
        lastSum  = list.get(i);
        if (lastSum < list.get(i)) {
            lastSum = list.get(i);
            lastSumStartIndex = i;
        }
        if (maxSum < lastSum) {
            maxSumStartIndex = lastSumStartIndex;
            maxSumLastIndex = i;
            maxSumLength = maxSumLastIndex - maxSumStartIndex   1;
            maxSum = lastSum;
        }
        if (maxSum == lastSum) {
            if (!(i - lastSumStartIndex   1 > maxSumLength)) continue;
            maxSumStartIndex = lastSumStartIndex;
            maxSumLastIndex = i;
            maxSumLength = maxSumLastIndex - maxSumStartIndex   1;
        }
    }
  • Related