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

算法练习(-)

作者: 杨柳小易 | 来源:发表于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);
}

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

相关文章

  • 前端干货 -03

    37. 算法 算法地址 数据结构与算法 JavaScript 描述. 章节练习https://github.com...

  • 算法-心得

    本周大部分的时间都在练习算法。虽说是有点被逼迫的意思,但是算法还是很重要的,也需要自己练习。 说到算法,我自身的感...

  • 算法练习(-)

    You are a professional robber planning to rob houses alon...

  • 算法练习

    将字符串转化为数字,实现int()方法 回文数 俩数之和 给定一个整数数组 nums 和一个目标值 target,...

  • 算法练习

    背景 Find closing/opening parenthesis You will be implement...

  • 算法练习

    2021 三月份 1. 两数之和 给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 ...

  • 刷算法 - 算法练习

    最近断断续续的刷了一些基础算法题. 我们做移动端开发的, 刷算法题有意义吗? 如果对这个问题有疑问, 可以在读这篇...

  • 2018-11-11 算法练习题

    下面是几道算法练习题:

  • iOS + 常用排序算法

    算练习吧参照的原文常用排序算法总结(一)八大排序算法

  • 笨办法学C 练习39:字符串算法

    练习39:字符串算法 原文:Exercise 39: String Algorithms 译者:飞龙 这个练习中,...

网友评论

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

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