我一直在尝试算法,用于获取数组中不相邻元素的最大和,但我想:
如果我们有一个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.
这只是我脑海中的一个想法,还没有超过这个长度。