java支持最大数字_java-构成最大和的数字

我刚刚编写了程序,该程序从数组中找到最大和,

但我陷入困境,有什么办法可以找到哪些数字促成了最高金额?

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 ex = new ArrayList<>();

List 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 ex = new ArrayList<>();

List inc = new ArrayList<>();

输入:-1 7 8 -5 4

输出:12

总和由8 4组成

输入:3 2 1 -1

输出4

总和由3 1组成

等等….

解决方法:

您可以遵循此代码.

int toIndex = 3, fromIndex = 0;

List result = new ArrayList<>();

while (toIndex < numbers.size()) {

Map 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));

https://www.icode9.com/content-1-551301.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值