feat: add Minimum Falling Path Sum (#1182)

Co-authored-by: David Leal <halfpacho@gmail.com>
This commit is contained in:
Alexander Pantyukhin 2023-01-18 23:54:30 +04:00 committed by GitHub
parent 36d1b265a7
commit 1b6fe6ea17
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 38 additions and 0 deletions

View File

@ -100,6 +100,7 @@
| 901 | [Online Stock Span](https://leetcode.com/problems/online-stock-span/) | [C](./src/901.c) | Medium | | 901 | [Online Stock Span](https://leetcode.com/problems/online-stock-span/) | [C](./src/901.c) | Medium |
| 905 | [Sort Array By Parity](https://leetcode.com/problems/sort-array-by-parity/) | [C](./src/905.c) | Easy | | 905 | [Sort Array By Parity](https://leetcode.com/problems/sort-array-by-parity/) | [C](./src/905.c) | Easy |
| 917 | [Reverse Only Letters](https://leetcode.com/problems/reverse-only-letters/) | [C](./src/917.c) | Easy | | 917 | [Reverse Only Letters](https://leetcode.com/problems/reverse-only-letters/) | [C](./src/917.c) | Easy |
| 931 | [Minimum Falling Path Sum](https://leetcode.com/problems/minimum-falling-path-sum/description/) | [C](./src/931.c) | Medium |
| 938 | [Range Sum of BST](https://leetcode.com/problems/range-sum-of-bst/) | [C](./src/938.c) | Easy | | 938 | [Range Sum of BST](https://leetcode.com/problems/range-sum-of-bst/) | [C](./src/938.c) | Easy |
| 965 | [Univalued Binary Tree](https://leetcode.com/problems/univalued-binary-tree/) | [C](./src/965.c) | Easy | | 965 | [Univalued Binary Tree](https://leetcode.com/problems/univalued-binary-tree/) | [C](./src/965.c) | Easy |
| 977 | [Squares of a Sorted Array](https://leetcode.com/problems/squares-of-a-sorted-array/) | [C](./src/977.c) | Easy | | 977 | [Squares of a Sorted Array](https://leetcode.com/problems/squares-of-a-sorted-array/) | [C](./src/977.c) | Easy |

37
leetcode/src/931.c Normal file
View File

@ -0,0 +1,37 @@
#define min(a,b) (((a)<(b))?(a):(b))
// Dynamic programming.
// Runtime O(n*n)
// Space O(n)
int minFallingPathSum(int** matrix, int matrixSize, int* matrixColSize){
int* dp = calloc(matrixSize, sizeof(int));
for (int i = 0; i < matrixSize; i++){
int* nextDp = calloc(matrixSize, sizeof(int));
for (int j = 0; j < matrixSize; j++){
nextDp[j] = dp[j] + matrix[i][j];
// If not the first column - try to find minimum in prev column
if(j > 0){
nextDp[j] = min(nextDp[j], dp[j - 1] + matrix[i][j]);
}
// If not the last column - try to find minimum in next column
if (j < matrixSize - 1){
nextDp[j] = min(nextDp[j], dp[j + 1] + matrix[i][j]);
}
}
free(dp);
dp = nextDp;
}
int result = dp[0];
for (int j = 1; j < matrixSize; j++){
result = min(result, dp[j]);
}
free(dp);
return result;
}