(greedy)Best Time to Buy and Sell Stock II
2024-10-01 07:05:28
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).
题目大意:
类似I,只不过现在允许进行多次交易,只需在上升曲线累加收益即可,即所谓的贪婪算法。
(贪婪算法与动态规划的区别:贪婪算法只需在每一步求出最大收益,即可在最后一步得到总的最大利润,而对于动态规划,每一步的最大收益可能受到前面某一步的影响,导致必须在最后一步综合前面的状态才能得出最大利润)
Java解法:
public class Solution {
public int maxProfit(int[] prices) {
if(prices == null || prices.length == 0)
return 0;
int profit = 0;
int temp = prices[0];
for(int i = 1; i<prices.length; i++){
if(prices[i] > temp) //上升曲线每步累加收益
profit += prices[i] - temp;
temp = prices[i];
}
return profit;
}
}
最新文章
- git查看本地和创建分支、上传分支、提交代码到分支、删除分支等,git分支、git查看本地和创建分支以及上传分支到服务器
- SqlLite 基本操作
- Android FragmentTransactionExtended:使Fragment以多种样式动画切换
- Java-继承,多态0922-05
- eclipse常用快捷键及调试方法(虽然现在看不懂,但是感觉以后肯定会用到,先转了)
- SQL Server 2008 R2——开发资料搜集
- js 原型的内存分析
- Azure SQL 数据库:服务级别与性能问答
- js事件模型
- bzoj 3043 (差分序列运用)
- Java中的HashMap和Hashtable
- JSP标准标签库(JSTL)--XML标签库 x
- hackerrank DFS Edges
- linux只端口监听及杀死进程
- Mybatis框架基础支持层——反射工具箱之泛型解析工具TypeParameterResolver(4)
- centos7.2 环境下 mysql-5.1.73 安装配置
- 模拟select控件,css模拟下拉
- java算法面试题
- c++ 容器填充指定长度(fill_n)
- OC基础:实例变量和成员变量的区别 分类: ios学习 OC 2015-06-14 17:59 16人阅读 评论(0) 收藏