[LeetCode] Best Time to Buy and Sell Stock II
2016-04-20 20:29
323 查看
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).
更上一题不同的是,这次是想交易多少次就交易多少次,不过每次只能进行一次交易,即交易不能重叠。
采用贪心法,如果有赚头就执行一次交易,这样就可以累计所有的价格增益。
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).
更上一题不同的是,这次是想交易多少次就交易多少次,不过每次只能进行一次交易,即交易不能重叠。
采用贪心法,如果有赚头就执行一次交易,这样就可以累计所有的价格增益。
/** * @param {number[]} prices * @return {number} */ var maxProfit = function(prices) { var prev = prices[0]; var profit = 0; prices.forEach(function(now) { if (now > prev){ profit += now - prev; } prev = now; }); return profit; };
相关文章推荐
- 3月23日 项目管理师作业
- nio体系介绍
- Linux内核-中断机制个人理解
- 小白python进击第二周2.尾递归
- awk笔记
- 六大设计原则(3)接口隔离原则
- 基于单目实现微型无人机感知和避撞
- pthread_create主线程与创建的新线程之间退出关系
- hdu5371回文串应用
- 复习数学之中国剩余定理和欧拉定理和扩展欧几里德
- Adapter数据变化改变现有View的实现原理及案例
- android基础---->发送和接收短信
- 一种简单的登录加密方案
- 进程间通信-信号量详解及编程实例
- java--web.xml中url-pattern的映射规则
- C++中lower_bound函数和upper_bound函数 以及 sort(参数)
- hdu 4638 Group(莫队算法)
- UVa1592_数据库
- 【NOIP2015模拟11.3】备用钥匙
- Ubuntu init启动流程分析