Skip to content

Commit 15ab7b3

Browse files
authored
Create minimum-falling-path-sum-ii.cpp
1 parent 1f3324a commit 15ab7b3

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

C++/minimum-falling-path-sum-ii.cpp

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
// Time: O(m * n)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
int minFallingPathSum(vector<vector<int>>& arr) {
7+
for (int i = 1; i < arr.size(); ++i) {
8+
const auto& smallest_two = nsmallest(2, arr[i - 1]);
9+
for (int j = 0; j < arr[0].size(); ++j) {
10+
arr[i][j] += (arr[i - 1][j] == smallest_two[0]) ? smallest_two[1] : smallest_two[0];
11+
}
12+
}
13+
return *min_element(arr.back().cbegin(), arr.back().cend());
14+
}
15+
16+
private:
17+
vector<int> nsmallest(int k, const vector<int>& arr) {
18+
priority_queue<int> max_heap;
19+
for (const auto& x : arr) {
20+
max_heap.emplace(x);
21+
if (max_heap.size() > k) {
22+
max_heap.pop();
23+
}
24+
}
25+
vector<int> result;
26+
while (!max_heap.empty()) {
27+
result.emplace_back(max_heap.top()); max_heap.pop();
28+
}
29+
return {result.crbegin(), result.crend()};
30+
}
31+
};

0 commit comments

Comments
 (0)