#include <stdio.h>
#define MAX_N 100
int dp_max(int a, int b)
{
return (a > b) ? a : b ;
}
/*
* Problem - Maximum Value Contiguous Subsequence / Maximum 1-D sum
* From a sequence of n integers a(1) ... a(n), determine a
* contiguous sub-sequence a(i) ... a(j) having the maximum sum of
* its elements.
*
*/
int dp_max_contiguous_subseq(int *arr, int len)
{
int i, j, m[MAX_N], max,
s=0, /* index of start of the sub-sequence */
e=0 ; /* index of end of the sub-sequence */
if (arr[0]<0) max = 0 ;
else max = arr[0] ;
for (m[0]=arr[0], j=1; j<len; j++) {
m[j] = dp_max(m[j-1]+arr[j], arr[j]) ;
if (m[j]>=max) {
max = m[j] ;
e = j ;
if (m[j] == arr[j])
s = j ;
}
}
printf("\n\nMax Contiguous Sequence starts@ %d and ends@ %d and sums to %d\n", s, e, max) ;
return max ;
}
int main()
{
int i, arr[MAX_N] ;
#ifndef ONLINE_JUDGE
freopen("dp_max_contiguous_subseq.in", "r", stdin) ;
#endif
i = 0 ;
while (scanf("%d", &arr[i]) != EOF) i++ ;
dp_max_contiguous_subseq(arr, i) ;
return 0;
}
Pages
Labels
01 Knapsack
(1)
Ad Hoc
(1)
Backtracking
(1)
Binary Search Tree
(1)
bits
(1)
Brute Force
(1)
codelib
(2)
Data Structures
(1)
Dijkstra
(1)
DP
(2)
Graphs
(1)
Heaps
(1)
Joseph
(1)
Maximum 1-D Sum
(1)
Maximum Contiguous Sum
(1)
Primes
(1)
Priority Queues
(1)
Recursion
(1)
Sieve of Atkins
(1)
UVaOJ Vol-102
(1)
UVaOJ Vol-109
(1)
UVaOJ Vol-5
(1)
Thursday, January 6, 2011
Maximum 1-D Sum
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment