50.Best Time to Buy and Sell Stock II(贪心算法)
2016-01-05 16:00
267 查看
题目原文:
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock
before you buy again).
分析:题目要求解是给定一个价格数组,然后设定算法对股票进行多次买卖操作,最终取得最大的利益。并且要求买一定要在卖的操作之前。
做这个题目的思路是用贪心的思想,选择价格数组中所有所有上涨价格段之和。即求价格曲线中所有价格上升段的长度之和。
代码如下:
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock
before you buy again).
分析:题目要求解是给定一个价格数组,然后设定算法对股票进行多次买卖操作,最终取得最大的利益。并且要求买一定要在卖的操作之前。
做这个题目的思路是用贪心的思想,选择价格数组中所有所有上涨价格段之和。即求价格曲线中所有价格上升段的长度之和。
代码如下:
/*可以允许买卖多次,采用贪心的策略*/ public int maxProfit(int[] prices) { int sum=0;//待返回的利益 int len = prices.length; for(int i =1;i<len;i++){ /*第i天的价格大于第i-1天的价格的时候,则第i-1天买,第i天卖*/ if(prices[i-1]<prices[i]){ sum += prices[i]-prices[i-1]; } } return sum; }
相关文章推荐
- 解析网络json数据,模拟美团界面显示。
- JavaScript 模块化及 SeaJs 源码分析
- 基于javascript实现图片懒加载
- 线程的7种状态及相互转换
- memset清空一个结构类型的变量或数组
- 【android】listview改变选中行背景图片
- 关于controller的瘦身计划
- iOS进阶面试题----经典10道
- C#多线程编程
- hash trick在机器学习中的使用
- sqlite系统学习网站
- git学习
- 40+ Sublime Text 最佳插件汇总
- python 数据类型之数值型
- 【第三节】android增量升级之提供服务端代码,整理项目
- 推荐系统中的match阶段
- javascript DOM 获取节点
- android adb命令
- 2. Add Two Numbers官方通过版本(8.46%)
- HBase 默认配置