[英]Maximum Sum Increasing Subsequence
So I made a simple python code using Dynamic programming to solve the problem of Maximum Increasing Subsequence.所以我用动态编程做了一个简单的python代码来解决最大递增子序列的问题。 The Question is as follows:
问题如下:
Given an array arr of N positive integers.给定一个由 N 个正整数组成的数组 arr。 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.输入:输入的第一行包含一个整数 T,表示测试用例的数量。 The first line of each test case is N(the size of array).
每个测试用例的第一行是 N(数组的大小)。 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'在我的解决方案中,我正在计算名为“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.
预期时间限制 < 2.32 秒提示:请优化您的代码并再次提交。
How do I optimise this code any further?如何进一步优化此代码?
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)在 O(n)
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])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.