forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
27 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
# Time: O(n * k) | ||
# Space: O(k) | ||
|
||
class Solution(object): | ||
def minCostII(self, costs): | ||
""" | ||
:type costs: List[List[int]] | ||
:rtype: int | ||
""" | ||
if not costs: | ||
return 0 | ||
|
||
n = len(costs) | ||
k = len(costs[0]) | ||
min_cost = [costs[0], [0] * k] | ||
for i in xrange(1, n): | ||
min_1st, min_2nd = float("inf"), float("inf") | ||
for j in xrange(k): | ||
if min_1st >= min_cost[(i - 1) % 2][j]: | ||
min_1st, min_2nd = min_cost[(i - 1) % 2][j], min_1st | ||
elif min_2nd >= min_cost[(i - 1) % 2][j]: | ||
min_2nd = min_cost[(i - 1) % 2][j] | ||
for j in xrange(k): | ||
min_j = min_1st if min_cost[(i - 1) % 2][j] != min_1st else min_2nd | ||
min_cost[i % 2][j] = costs[i][j] + min_j | ||
|
||
return min(min_cost[(n - 1) % 2]) |