I have a maxArray list that is controlled by an if statement saying if the sum of the current stack is greater than the maxSum to then update the maxArray to return, the maxSum value is not affected incorrectly, however the maxArray value changes to the latest update of the current stack even though the if statement is the only way to update the maxArray.
def maxSumIncreasingSubsequence(array):
# Write your code here.
maxArray = [array[0]]
maxSum = array[0]
stack = [array[0]]
for i in range(1,len(array)):
if len(stack) == 0:
stack.append(array[i])
else:
try:
while stack[-1] > array[i]:
stack.pop()
except:
pass
stack.append(array[i])
if sum(stack) > maxSum:
maxArray = stack
maxSum = sum(stack)
return([maxSum,maxArray])
test = [10, 70, 20, 30, 50, 11, 30]
print(maxSumIncreasingSubsequence(test))
for example given the values
[10, 70, 20, 30, 50, 11, 30]
the code should return
[110, [10, 20, 30, 50]]
but it returns
[110, [10, 11, 30]]