【LeetCode】122.Best Time to Buy and Sell Stock II解题报告
来源:互联网 发布:吸尘器手持 卧式 知乎 编辑:程序博客网 时间:2024/06/07 13:33
【LeetCode】122.Best Time to Buy and Sell Stock II解题报告
tags: Array Greedy
题目地址:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/#/description
题目描述:
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).
Solutions:
public class Solution { public int maxProfit(int[] prices) { int profit = 0; for (int i = 0; i < prices.length - 1; i++) { int diff = prices[i+1] - prices[i]; if (diff > 0) { profit += diff; } } return profit; }}
解题思路:
在Best Time to Buy and Sell Stock系列中,和本题最像的是Best Time to Buy and Sell Stock IV
Best Time to Buy and Sell Stock IV中是求某个给定k次交易的最大收益,和Maximum Subarray III完全一样
本题由于是可以操作任意次数,只为获得最大收益,而且对于一个上升子序列,比如:[5, 1, 2, 3, 4]中的1, 2, 3, 4序列来说,
对于两种操作方案:
1 在1买入,4卖出
2 在1买入,2卖出同时买入,3卖出同时买入,4卖出
这两种操作下,收益是一样的。所以可以从头到尾扫描prices,如果price[i] – price[i-1]大于零则计入最后的收益中。即贪心法
Date:2017年6月3日
- [leetcode] 122. Best Time to Buy and Sell Stock II 解题报告
- LeetCode 122. Best Time to Buy and Sell Stock II 解题报告
- Leetcode 122. Best Time to Buy and Sell Stock II 股票买卖2 解题报告
- LeetCode解题报告 122. Best Time to Buy and Sell Stock II [medium]
- [Leetcode] 122. Best Time to Buy and Sell Stock II 解题报告
- 【LeetCode】122.Best Time to Buy and Sell Stock II解题报告
- LeetCode-Best Time to Buy and Sell Stock-解题报告
- 【LeetCode】Best Time to Buy and Sell Stock 解题报告
- 【LeetCode】 Best Time to Buy and Sell Stock I II III IV 解题报告
- LeetCode-Best Time to Buy and Sell Stock II-解题报告
- 【LeetCode】 Best Time to Buy and Sell Stock I II III IV 解题报告
- 【LeetCode】Best Time to Buy and Sell Stock II 解题报告
- LeetCode 122. Best Time to Buy and Sell Stock II
- [Leetcode] 122. Best Time to Buy and Sell Stock II
- [leetcode] 122.Best Time to Buy and Sell Stock II
- 【leetcode】122.Best Time to Buy and Sell Stock II
- 【LeetCode】122.Best Time to Buy and Sell Stock II
- [leetcode] 122. Best Time to Buy and Sell Stock II
- Centos 7.3 本地YUM
- Vertx:ServiceDiscovery跟EventBus有啥关系?
- java基础教程:基础语法之变量常量(3)
- Maven中手动添加jar包
- 和她正式认识之前,我见过她三次
- 【LeetCode】122.Best Time to Buy and Sell Stock II解题报告
- 使用FPDF输出中文
- 之江学院2017ACM 校赛 Problem M: qwb与二叉树(记忆化搜索)
- 【数据压缩】Exp05.JPEG解码
- jdbc基础
- 文章标题 CSU 1849: Comparing answers(矩阵降维+随机化思想)
- android DroidPlugin 学习
- centos7安装telnet服务
- java锁机制