So, I have to find the maximum Sum of the continuous subset, I followed this algorithm in python.
def SubSeq(list):
final_list = None
suming = 0
for start in range(len(list)):
for end in range(start+1, len(list)+1):
subseq = list[start:end]
summation= sum(list[start:end])
if summation > suming:
suming = summation
final_list = subseq
return final_list
print SubSeq([5, 15, -30, 10, -5, 40, 10])
I wonder if it is a correct way in dynamic programming though the running time is O(n^2)
. Plus, is there a possible way to make it O(n)
This is not Dynamic Programming, it is a brute force solution. The solution seems to be correct, but as you observer - it is inefficient.
An O(n) solution can be achieved by applying Dynamic Programming, denote
D(i)
as the maximum sub contiguous subarray that ends ini
, and must includei
.The idea is, you have two choices - get the previously "best" array that ends at
i-1
and add elementi
to it, or create a new one that starts withi
.At the end, by applying the above in a DP solution, you get an array where each element indicates the maximum sub contiguous array ending with this index, all you have to do is choose the maximal value out of this array to get the value of the maximal sum, and go back on the array to get the actual subsequence.
Example:
Applying the dynamic programming:
And now you have the array:
The maximal subsequence's value is 55, and is given by
[10,-5,40,10]
(following the above array, and going back on it)