美文网首页
算法练习(-)

算法练习(-)

作者: 杨柳小易 | 来源:发表于2017-05-15 16:47 被阅读32次

    You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
    Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police

    这是一个算法题目:大致意思是说,有那么一个小偷,要去偷一条街道,每一家的钱都是已知的,不能偷相邻的两家,不然会触发报警系统。原谅我半吊子英语

    所以题目的变种就是有一个数组,里面存的整数,并且大于等于0,挑出最大的和,并且不能有相邻的数字。比如

    <code>NSArray *a = @[@(20),@(1),@(2),@(3)];</code>
    最大和就应该是23

    解法:
    <code>iOS</code>代码:

    NSUInteger max(NSUInteger a, NSUInteger b) {
        return  a>b?a:b;
    }
    
    NSUInteger maxNumber(NSArray *nums) {
        NSUInteger result = 0;
        
        ///观察最大的值变化
        NSMutableArray *max = [NSMutableArray new];
        for (int i = 0; i < nums.count; ++i) {
            NSUInteger n1 = 0;
            NSUInteger n2 = 0;
            NSUInteger n;
            if (i - 2 >= 0) {
                n1 = [max[i - 2] integerValue];
            }
            if (i - 3 >= 0) {
                n2 = [max[i - 3] integerValue];
            }
            
            if (n1 > n2) {
                n = [nums[i] integerValue] + n1;
            } else {
                n = [nums[i] integerValue] + n2;
            }
            if (n > result) {
                result = n;
            }
            [max addObject:@(n)];
        }
        
        [max enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSLog(@"🐒🐒🐒🐒 =   %@",obj);
        }];
        
        return result;
    }
    
    

    上面的思路是,创建了一个数组保存每个下标的最大和,减2 减3 的意思是当前的最大和应该是加上他之前的相邻的最大和,因为没有负数,所以隔一个两个应该就是最大的值了。正确性还在验证。。

    NSUInteger rob(NSArray *nums) {
        NSUInteger a = 0, b = 0;
        for (int i = 0; i < nums.count; ++i) {
            if(i % 2 == 0)a = max(a+[nums[i] integerValue],b);
            else b = max(b+[nums[i] integerValue],a);
            
            NSLog(@"%@ %@", @(a),@(b));
        }
        return max(a,b);
    }
    
    

    上面的思路就是分奇数偶数计算各自最大的,然后值保留最大的,最后比较一下输出。

    相关文章

      网友评论

          本文标题:算法练习(-)

          本文链接:https://www.haomeiwen.com/subject/bjphxxtx.html