0

So I made a simple python code using Dynamic programming to solve the problem of Maximum Increasing Subsequence. The Question is as follows:

Given an array arr of N positive integers. Find the sum of maximum sum increasing subsequence of the given array.

Input: The first line of input contains an integer T denoting the number of test cases. The first line of each test case is N(the size of array). The second line of each test case contains array elements.

Output: For each test case print the required answer in new line.

In my solution I am calculating the maximum sum in a list called 'sums'

#code
T = int(input())
for _ in range(T):
    N = int(input())
    arr = list(map(int, input().split()))
    sums = list(arr)
    max_sum = arr[0]

    for j in range(1,N):
        for i in range(0,j):
            if arr[i]<arr[j] and sums[j]<sums[i]+arr[j]:
                sums[j] = (sums[i]+arr[j])
                if sums[j]>max_sum:
                    max_sum = sums[j]

    print(max_sum)

My Output: Your program took more time than expected.Time Limit Exceeded. Expected Time Limit < 2.32sec Hint : Please optimize your code and submit again.

How do I optimise this code any further?

2 Answers2

0

I think this will work

def max_inc(a):
    max = a[0]
    prev = a[0]
    current = a[0]
    for i in range(1,len(a)):
        if a[i]>prev:
            current+=a[i]
            if current>max:
                max = current
        else:
            current = 0
        prev = a[i]
    return max

in O(n)

trigonom
  • 528
  • 4
  • 9
0

More Readability:

def maxSumIncreasingSubsequence(array):

    sums = [num for num in array]
    maxSumIdx = 0

    for i in range(len(array)):
        currVal = array[i]
        for j in range(i):
            prevVal = array[j]
            if currVal > prevVal and sums[j] + currVal >= sums[i]:
                sums[i] = sums[j] + currVal
     
        if sums[i] >= sums[maxSumIdx]:
            maxSumIdx = i

    return sums[maxSumIdx] 

T = int(input())
for _ in range(T):
    N = int(input())
    arr = list(map(int, input().split()))
    maxSumIncreasingSubsequence([10, 70, 20, 30, 50, 11, 30])
Vishal Singh
  • 725
  • 7
  • 16