The actual problem statement was like 4 sentences long, but it boils down to the following:
Given a list of lists as input (triangle format), return a string that represents the turns it took to get the maximum top-to-bottom path sum.
Example:
Input: [ [1],
------ [3], [5],
---- [8], [10], [4] ]
^ignore dashes, I'm using them for indentation
Output: "RL"
^ This value corresponds to the path 1->5->10 whose sum is 16 (the maximum top-to-bottom path sum). This is because from the top, we went down right, "R", then down left, "L".
A correct pseudo solution:
It's similar to: https://leetcode.com/problems/triangle/. Part of the question involves getting the maximum sum path version of the triangle question. The difference is in providing a different output.
Here's the most efficient way to get the maximum path sum (it's bottom-up b/c the top-down has a higher space complexity):
Time: O(n^2) due to double iteration and O(n) space due to res.
class Solution(object):
def maximumTotal(self, triangle):
# edge case
if not triangle:
return
# init return value (O(n) space)
res = triangle[-1]
# enter and iterate the list of lists using double for loop, (this nested loop is the cause of O(n^2) time)
for i in xrange(len(triangle)-2, -1, -1):
for j in xrange(len(triangle[i])):
res[j] = max(res[j], res[j+1]) + triangle[i][j]
return res[0]Anyone have the correct way to add on to this, such that we get the correct output using the hastable methodology explained in the pseudo? Or any other approaches in general?