Given a triangle array, return the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
Example:
Input: triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]
Output: 11
Explanation: The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11.
Constraints:
1 <= triangle.length <= 200
triangle[0].length == 1
triangle[i].length == i + 1
for i >= 0
-10^4 <= triangle[i][j] <= 10^4
Q: Can the triangle array have only negative numbers? A: Yes, the elements can be negative as per the constraints.
Q: Do we need to consider only non-diagonal paths? A: No, each step can move to an adjacent number on the row below.
We can solve this problem using dynamic programming. We’ll modify the given triangle in place to store the minimum path sums that lead to each element. We start from the second last row and move upwards, updating the minimum path sum for each element by considering the minimum path sum from the elements directly below it.
Here are the steps to solve the problem:
Here is the implementation in Python:
def minimumTotal(triangle):
# Start from the second last row
for row in range(len(triangle) - 2, -1, -1):
for col in range(len(triangle[row])):
# Update the current element with the minimum path sum
triangle[row][col] += min(triangle[row+1][col], triangle[row+1][col+1])
# The top element now contains the minimum path sum
return triangle[0][0]
The time complexity of this solution is O(n^2)
, where n
is the number of rows in the triangle. This is because every element in the triangle is processed a constant number of times (each element is updated once).
The space complexity is O(1)
extra space since we are modifying the triangle in place and not using any additional data structures.
This approach ensures that the problem is solved efficiently both in terms of time and space.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?