我需要找到非连续子序列的最大总和,我有以下代码。
public int maxSumInSubsequence(int[] data) {
if (data == null) return 0;
int n = data.length;
// maxSum[i] == the maximum sum of subsequences of data[0 .. i] that include data[i]
int[] maxSum = new int[n];
for (int i=0; i<n; ++i) {
maxSum[i] = data[i];
// maxSum[i-1] includes data[i-1] and thus cannot include data[i]
for (int j=0; j<i-1; ++j) {
maxSum[i] = Math.max(data[i] + maxSum[j], maxSum[i]);
}
}
// find the max of all subsequences
int max = 0;
for (int i=0; i<n; ++i) {
max = Math.max(max, maxSum[i]);
}
return max;
}
这样可以正常工作,但如何修改它以排除计算中的第一个和最后一个元素。
答案 0 :(得分:2)
i
元素,长度为n-1
,包围数组。此外,正如另一个答案所述,maxSumInSubsequence
可以优化,以便O(n)
时间复杂。
public int maxSumInSubsequence(int[] data) {
if (data == null) return 0;
int n = data.length;
if (n <= 2) return 0;
// maxSum[i] == the maximum sum of subsequences of data[0 .. i] that include data[i]
int[] maxSum = new int[n];
for (int i=0; i<n; ++i) {
maxSum[i] = data[i];
// maxSum[i-1] includes data[i-1] and thus cannot include data[i]
for (int j=0; j<i-1; ++j) {
maxSum[i] = Math.max(data[i] + maxSum[j], maxSum[i]);
}
}
// find the max of all subsequences
int max = 0;
for (int i=0; i<n; ++i) {
max = Math.max(max, maxSum[i]);
}
return max;
}
public int maxCircularSumInSubsequence(int[] data) {
int n = data.length;
int max = 0;
for (int i = 0; i < n; i++) {
int[] circularData = new int[n-1];
for (int j = 0; j < n - 1; j++) {
circularData[j] = data[(i+j) % n];
}
max = Math.max(maxSumInSubsequence(circularData), max);
}
return max;
}
答案 1 :(得分:0)
/*Function to return max sum such that no two elements
are adjacent */
int FindMaxSum(int arr[], int n)
{
int incl = arr[0];
int excl = 0;
int excl_new;
int i;
for (i = 1; i < n; i++)
{
/* current max excluding i */
excl_new = (incl > excl)? incl: excl;
/* current max including i */
incl = excl + arr[i];
excl = excl_new;
}
/* return max of incl and excl */
return ((incl > excl)? incl : excl);
}
参考:http://www.geeksforgeeks.org/maximum-sum-such-that-no-two-elements-are-adjacent/
答案 2 :(得分:0)
基本逻辑是计算两种可能性的总和:从0开始 i 然后与每个备用数组no相加或使用开始 i 我并从那里总结每个替代号码并打印两者的最大值。
arr=[5,5,10,100,10,50,1]
def max_sum_suchThatNoTwoElements_are_adjacent(arr,n,su,max_sum):
i=0
while i<n:
su+=arr[i]
if (i+1)<n:
max_sum+=arr[(i+1)]
i+=2
return max(max_sum,su)
print(max_sum_suchThatNoTwoElements_are_adjacent(arr,len(arr),0,0))