C# Solution inspired by House Robber I


  • 0
    L

    my idea is to get rid of the effect of the circle, so I remove the first element from the circle, and the question becomes: the max result between the solution includes 1st and the solution do not includes 1st

    public class Solution {
        public int Rob(int[] nums) {
            var result = 0;
                if (nums != null && nums.Length > 0)
                {
                    if (nums.Length == 1)
                        result = nums[0];
                    else if (nums.Length == 2)
                        result = Math.Max(nums[0], nums[1]);
                    else
                    {
                        var contain1 = GetN(nums, 2, nums.Length - 2  )+ nums[0];
                        var containNo1 = GetN(nums, 1, nums.Length - 1);
                        result = Math.Max(contain1, containNo1);
                    }
    
                }
                return result;
        }
        
        
        
        public int GetN(int[] nums, int start, int end)
            {
                var result = 0;
                if (nums != null && nums.Length > 0&& end >= start)
                {
                    result = nums[start];
                    var containn_1 = nums[start];
                    var containNon_1 = 0;
                    for (int i = start+1; i <= end; i++)
                    {
                        containn_1 = containNon_1 + nums[i];
                        containNon_1 = result;
                        result = Math.Max(containNon_1, containn_1);
                    }
                }
                return result;
            }
            
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.