我一直在玩与周围的算法得到的最大的一笔在一个阵列是两个相邻的元素一点,但我想顶多两个连续的元素:找到最大的总和,包括从一个数组
如果我们有一个包含n个元素的数组,我们希望找到最大的总和,以便3个元素永不碰触。这就是说,如果我们有数组a = [2,5,3,7,8,1],我们可以选择2和5,但不是2,5和3,因为我们有3个连续的数组。这个规则的最大和总和为:22(2和5,7和8,2 + 5 + 7 + 8 = 22)
我不知道我将如何实现这一点,任何想法?
编辑:
我只走了这么远,想想可能是什么好做:
我们只是坚持在同一个阵列:
int[] a = {2, 5, 3, 7, 8, 1};
int{} b = new int[n}; //an array to store results in
int n = a.length;
// base case
b[1] = a[1];
// go through each element:
for(int i = 1; i < n; i++)
{
/* find each possible way of going to the next element
use Math.max to take the "better" option to store in the array b*/
}
return b[n]; // return the last (biggest) element.
这只是我头脑里想到的一个念头,并没有超过这个。
向我们展示你已经尝试什么 –
我没有把任何代码,只是想着这个。基本情况当然是第一个元素,对于其他情况,我认为最好将已有的结果存储在数组中。然后,我可以将数组中的数据与Math.max(possible1 + Array [latest-element],possible2 + Array [latest-2-element])进行比较,因为在您到达之前您无法知道下一个元素。在for循环中通过数组。但我的思想中只有这么“远”。 – Mappan