分享

java-构成最大和的数字

 印度阿三17 2019-11-08

我刚刚编写了程序,该程序从数组中找到最大和,
但我陷入困境,有什么办法可以找到哪些数字促成了最高金额?

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

我对数组中最大和的解决方案:

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;
    }
}

现在在最大函数中有一个调整,可以将构成最大和的所有元素索引放到哪里?

输入:

-1 7 8 -5 4 9 -2 3

输出:

20

**

我需要20点到达.答案应该是8 9 3

**

我相信在最大功能中,我们可以放置一个Arraylist并记录哪些元素对总和起作用,但我无法实现.

我做了两个Arraylist:

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

输入:-1 7 8 -5 4
输出:12
总和由8 4组成

输入:3 2 1 -1
输出4
总和由3 1组成

等等….

解决方法:

您可以遵循此代码.

    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

来源:https://www./content-1-551301.html

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多