Given a 2D array
For each step, you may move to an adjacent index number of the row below.
More formally, if you are on index
Output: 11
Explanation: The triangle looks like this
[
[
[6,
[4,
So, minimum path sum will be 2 + 3 + 5 + 1 = 11
Output: 11
Explanation: The triangle looks like this
[
[6,
[5,
[2,
So, minimum path sum will be 2 + 4 + 2 + 3 = 11
Output: -10
Contents
Solution using depth first search recursively Solution using dynamic programming memoization
In this approach, we will compute the mininum value from adding bottom row
-
When we are at the last row,
Min number will be itself as there is no row aftre that or you can assume that there is row with all 0's. -
Calculate Min possible value using
Min(triangle[row][column] + minimumTotal(triangle[row+1][column]), triangle[row][column] + minimumTotal(triangle[row+1][column+1])) - For example, if we visualize the recursive solution for input [[2], [3, 4], [6, 5, 7], [4, 1, 8, 3]], it looks like below diagram.

Complexity Analysis:
Time complexity: Above code runs in O(2n) time where
Space complexity: O(n) where n is the size of input array.
In this approach, we are going to solve the problem using below steps.
-
Create a temporary array with size as last row size +1.
int[] temp = new int[triangle.get(triangle.size-1).size() + 1] -
We are going to store the
mininum path sum computed into this temporary array, by looking at Min(currentElement +ith indexed number from temporary array, currentElement +i + 1th indexed number from temporary array) - When we are done with all rows from triangle, first element in the temporary array is our answer. Calculating minimum path sum in bottom - up approach looks like below diagram.
-
If you notice we are only maintaining temporary array with size as last sub array size of
triangle array in each iteration.

Complexity Analysis:
Time complexity: Above code runs in O(n * m) time where
Space complexity: O(n) where n is the bottom sub array size.
Above implementations source code can be found at