贪心算法的核心思想是在每一步决策中都找到局部最优解
class Solution { public int maxProfit(int[] prices) { int n = prices.length; int profit = 0; int price = prices[0]; for(int i = 1; i < n; i++){ price = prices[i-1]; if(prices[i]>price){ profit += (prices[i] - price); } } return profit; } }
去看今天的股票价格是否大于昨天的就可以了,如果大于的话,那返回值就加上他们的差价。
class Solution { public boolean canJump(int[] nums) { int n = nums.length; if(n == 1){ return true; } int longest = 0; for(int i = 0; i<= longest; i++){ longest = Math.max(longest, i + nums[i]); if(longest >= n-1){ return true; } } return false; } }
每次取数组中已经经过的最大值,去看他们最远是否可以覆盖到数组长度-1, 如果覆盖面全都无法达到,那么就返回false;
class Solution { public int jump(int[] nums) { int n = nums.length; int res = 0; int end = 0; int temp = 0; for(int i = 0; i<=end ; i++){ if(end >= n-1){ return res; } temp = Math.max(temp, i + nums[i]); if(i == end){ end = temp; res++; } } return res; } }
和上一题思路基本相似,只不过要在不断扩大覆盖面积后加上1,用来计算重新覆盖的次数
今天是贪心算法,第一天感觉良好
原文地址:http://www.cnblogs.com/catSoda/p/16883877.html
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,请务用于商业用途!
3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需!
7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员!
8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载
声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性