[Algorithm] 122. Best Time to Buy and Sell Stock II
2024-09-03 10:27:14
Previous one: https://www.cnblogs.com/Answer1215/p/11974453.html
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 (i.e., buy one and sell one share of the stock multiple times).
Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).
Input: [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
engaging multiple transactions at the same time. You must sell before buyingInput: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
var maxProfit = function(prices) {
let sum = ;
for (let i = ; i < prices.length; i++) {
sum += Math.max(, prices[i] - prices[i-]);
} return sum
};
最新文章
- 【原创经验分享】WCF之消息队列
- [Shell] 文件名截取的问题:bash .vs. csh
- MySQL数据库学习笔记(四)----MySQL聚合函数、控制流程函数(含navicat软件的介绍)
- Objective-C中NSValue的使用
- 使用selector修改TextView中字体的颜色
- Struck: Structrued Output Tracking with Kernels 论文笔记
- Citrix 服务器虚拟化之三十二 XenConvert
- Python:一篇文章掌握Numpy的基本用法
- 201521123012 《Java程序设计》第四周学习总结
- 201521123002《Java程序设计》第14周学习总结
- ansible服务及剧本编写
- ●洛谷 P3616 富金森林公园
- C++将十进制数转化为二进制
- HTML/overflow的认识
- hadoop distcp 命令&; 不同hadoop 版本cp
- 四则运算(Java)--温铭淇,付夏阳
- 【转载】MFC动态创建控件及其消息响应函数
- 模型构建<;3>;:交叉验证
- Blueprint 编译概述
- 百度2017春招<;度度熊回家问题>;