Untitled

mail@pastecode.io avatar
unknown
elm
2 years ago
2.8 kB
1
Indexable
Never
import java.util.Scanner;
import java.util.ArrayList;

public class Main9 {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        ArrayList<Integer> list1 = new ArrayList<>();
        System.out.print("Введите массив с элементами через пробел: ");
        String str = in.nextLine();
        String[] numbers = str.split(" ");
        for (String number : numbers) {
            list1.add(Integer.parseInt(number));
        }

        ArrayList<Integer> answerList = createNewList(list1);
        for (Integer x : answerList) {
            System.out.print(x + " ");
        }
    }
    public static ArrayList<Integer> createNewList(ArrayList<Integer> list) {
        ArrayList<Integer> answerListTemp = new ArrayList<>();
        ArrayList<Integer> answerList = new ArrayList<>();
        int i = 1;

        while(i<list.size()){

            if(list.get(i-1)<=list.get(i)) {
                if(answerListTemp.isEmpty())
                    answerListTemp.add(list.get(i-1));
                answerListTemp.add(list.get(i));
            } else {
                sorting(answerListTemp, answerList);
            }
            i++;
        }
        if (!answerListTemp.isEmpty()) {
            if (answerListTemp.size() > answerList.size()) {
                return answerListTemp;
            } else {
                if (answerList.size() == answerListTemp.size())
                    compareSum(answerListTemp, answerList);
            }
        }

        return answerList;
    }
    public static ArrayList<Integer> sorting(ArrayList<Integer> answerListTemp, ArrayList<Integer> answerList) {
        if(!answerListTemp.isEmpty()) {
            if(!answerList.isEmpty()){
                if(answerList.size()<answerListTemp.size()){
                    answerList.clear();
                    answerList.addAll(answerListTemp);
                    answerListTemp.clear();
                } else if (answerList.size()==answerListTemp.size())
                    compareSum(answerListTemp, answerList);
                answerListTemp.clear();
            } else {
                answerList.addAll(answerListTemp);
                answerListTemp.clear();
            }
        }
        return answerList;
    }
    public static void compareSum(ArrayList<Integer> answerListTemp, ArrayList<Integer> answerList) {
        double sum = 0;
        double sumTemp = 0;
        for (int j = 0; j < answerList.size(); j++) {
            sum += answerList.get(j);
            sumTemp += answerListTemp.get(j);
        }
        if(sum<sumTemp) {
            answerList.clear();
            answerList.addAll(answerListTemp);
            answerListTemp.clear();
        }
    }
}