File tree Expand file tree Collapse file tree 2 files changed +40
-0
lines changed
kotlin/Dynamic Programming Expand file tree Collapse file tree 2 files changed +40
-0
lines changed Original file line number Diff line number Diff line change
1
+ fun neighborhoodBurglaryOptimized (houses : List <Int >): Int {
2
+ if (houses.isEmpty()) {
3
+ return 0
4
+ }
5
+ if (houses.size == 1 ) {
6
+ return houses[0 ]
7
+ }
8
+ // Initialize the variables with the base cases.
9
+ var prevMaxProfit = maxOf(houses[0 ], houses[1 ])
10
+ var prevPrevMaxProfit = houses[0 ]
11
+ for (i in 2 until houses.size) {
12
+ val currMaxProfit = maxOf(prevMaxProfit, houses[i] + prevPrevMaxProfit)
13
+ // Update the values for the next iteration.
14
+ prevPrevMaxProfit = prevMaxProfit
15
+ prevMaxProfit = currMaxProfit
16
+ }
17
+ return prevMaxProfit
18
+ }
Original file line number Diff line number Diff line change
1
+ fun neighborhoodBurglary (houses : List <Int >): Int {
2
+ // Handle the cases when the array is less than the size of 2 to
3
+ // avoid out-of-bounds errors when assigning the base case values.
4
+ if (houses.isEmpty()) {
5
+ return 0
6
+ }
7
+ if (houses.size == 1 ) {
8
+ return houses[0 ]
9
+ }
10
+ val dp = IntArray (houses.size)
11
+ // Base case: when there's only one house, rob that house.
12
+ dp[0 ] = houses[0 ]
13
+ // Base case: when there are two houses, rob the one with the most
14
+ // money.
15
+ dp[1 ] = maxOf(houses[0 ], houses[1 ])
16
+ // Fill in the rest of the DP array.
17
+ for (i in 2 until houses.size) {
18
+ // 'dp[i]' = max(profit if we skip house 'i', profit if we rob house 'i').
19
+ dp[i] = maxOf(dp[i - 1 ], houses[i] + dp[i - 2 ])
20
+ }
21
+ return dp[houses.size - 1 ]
22
+ }
You can’t perform that action at this time.
0 commit comments