File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change
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
+ };
You can’t perform that action at this time.
0 commit comments