Geeks面试题: Maximum Sum Increasing Subsequence

Maximum Sum Increasing Subsequence

Given an array of n positive integers. Write a program to find the sum of maximum sum subsequence of the given array such that the intgers in the subsequence are sorted in increasing order. For example, if input is {1, 101, 2, 3, 100, 4, 5}, then output should be 106 (1 + 2 + 3 + 100), if the input array is {3, 4, 5, 10}, then output should be 22 (3 + 4 + 5 + 10) and if the input array is {10, 5, 4, 3}, then output should be 10

Solution
This problem is a variation of standard Longest Increasing Subsequence (LIS) problem. We need a slight change in the Dynamic Programming solution of LIS problem. All we need to change is to use sum as a criteria instead of length of increasing subsequence.

下面程序是我的解决方法,时间效率也是O(n*n) 思路:

1 从底往上解决法

2 计算当前数值到下一个数值是否是递增,如果是递增,后面所有数值的递增数列加上当前数值

3 一直计算到最后,就得到数列中所有数值以自己为结束的最大递增子段和

因为有可能以最后一个数值结束的递增子段和不是总体得到的最大递增子段和,例如: 3 11 2 10填表得到: 3 14 2 12,那么最大递增子段和是14,不是12

所以需要最后比较数组中所有数值,求最大值,当然也可以如下面第二个程序一边求解一边判断最大值,填表得到的是3 14 14 14,那么返回表的最后一个数值就可以了

Geeks上的原文总体算法和我的差不多的,不过细节处理上有区别,效率一样。

int maxSumISDP( int arr[], int n )
{
	vector<int> ta(arr, arr+n);
	for (int i = 0; i < n; i++)
	{
		for (int j = i+1; j < n; j++)
		{
			if (arr[j] > arr[i]) ta[j] = arr[j] + ta[i];//=arr[i] + ta[j];
		}
	}
	int maxsum = INT_MIN;
	for (int i = 0; i < n; i++)
	{
		maxsum = max(maxsum, ta[i]);
	}
	return maxsum;
}

int maxSumISDP2( int arr[], int n )
{
	vector<int> ta(arr, arr+n);
	for (int i = 0; i < n; i++)
	{
		for (int j = i+1; j < n; j++)
		{
			if (arr[j] > arr[i]) ta[j] = arr[j] + ta[i];//=arr[i] + ta[j];
		}
		if (i>0) ta[i] = max(ta[i], ta[i-1]);
	}
	return ta[n-1];
}














Geeks面试题: Maximum Sum Increasing Subsequence

上一篇:ubuntu12.04下配置jdk6 6u38版的最新方法


下一篇:SqlHelper