LeetCode House Robber II,leetcoderobber

來源:互聯網
上載者:User

LeetCode House Robber II,leetcoderobber
LeetCode House Robber II題目

思路

思路來源於Discuss。
一是在Robber這題中的O(n)解法;
二是在Robber這題中,我們只需要分別考慮包含了nums[0]和nums[n-1]的情況即可。
注意這裡的包含並不是說Robber一定要偷num[0]或nums[n-1],只是說考慮進去的意思。

代碼
#define max(a, b) ((a)>(b)?(a):(b))int rob(int* nums, int numsSize) {    if (numsSize <= 0) return 0;    if (numsSize == 1) return nums[0];    int evenMax, ooddMax, include0, i;    for (i = evenMax = ooddMax = 0; i < numsSize - 1; i++)  // 包含nums[0]        if (i % 2) ooddMax = max(ooddMax + nums[i], evenMax);        else evenMax = max(evenMax + nums[i], ooddMax);    include0 = max(evenMax, ooddMax);    for (i = 1, evenMax = ooddMax = 0; i < numsSize; i++)  // 包含nums[n-1]        if (i % 2) ooddMax = max(ooddMax + nums[i], evenMax);        else evenMax = max(evenMax + nums[i], ooddMax);    return max(include0, max(evenMax, ooddMax));}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.