The code provided solves the House Robber II problem, which involves finding the maximum sum of non-adjacent elements in a circular array (since the first and last elements are adjacent in a circle).
You are a robber trying to maximize the amount of money you can steal from houses arranged in a circle. You cannot steal from two adjacent houses (including the first and last, as they are circularly adjacent).
The key insight for circular arrays is to split the problem into two linear subproblems:
0 to n-2.1 to n-1.The result is the maximum of these two cases, as you cannot steal from both the first and last house in a circular arrangement.
The helper function rob solves the linear version of the problem (House Robber I) using dynamic programming with O(1) space complexity:
prev_prev and prev) to store the maximum sum up to the previous two houses.The code handles all edge cases:
The helper function uses O(1) space and O(n) time, making the overall solution efficient (O(n) time, O(1) space).
The code is correct and efficiently solves the House Robber II problem. It correctly splits the circular problem into linear subproblems and uses optimal dynamic programming for each subproblem.
Final Answer: This code solves the House Robber II problem, finding the maximum sum of non-adjacent elements in a circular array. The correct approach is implemented, and the code is efficient and handles all edge cases. For example, if input is [2,3,2], the output is 3; if input is [1,2,3,1], output is 4. The code's solution is optimal.
def max_sum_non_adjacent(nums):
if len(nums) <= 1:
return sum(nums)
def rob(sub_nums):
if not sub_nums:
return 0
if len(sub_nums) == 1:
return sub_nums[0]
prev_prev = 0
prev = sub_nums[0]
for i in range(1, len(sub_nums)):
current = max(prev, prev_prev + sub_nums[i])
prev_prev, prev = prev, current
return prev
case1 = rob(nums[:-1]) # Exclude last element
case2 = rob(nums[1:]) # Exclude first element
return max(case1, case2)
# Example usage:
# print(max_sum_non_adjacent([2,3,2])) → Output:3
# print(max_sum_non_adjacent([1,2,3,1])) → Output:4
(免責(zé)聲明:本文為本網(wǎng)站出于傳播商業(yè)信息之目的進(jìn)行轉(zhuǎn)載發(fā)布,不代表本網(wǎng)站的觀點(diǎn)及立場(chǎng)。本文所涉文、圖、音視頻等資料的一切權(quán)利和法律責(zé)任歸材料提供方所有和承擔(dān)。本網(wǎng)站對(duì)此資訊文字、圖片等所有信息的真實(shí)性不作任何保證或承諾,亦不構(gòu)成任何購(gòu)買、投資等建議,據(jù)此操作者風(fēng)險(xiǎn)自擔(dān)。) 本文為轉(zhuǎn)載內(nèi)容,授權(quán)事宜請(qǐng)聯(lián)系原著作權(quán)人,如有侵權(quán),請(qǐng)聯(lián)系本網(wǎng)進(jìn)行刪除。