122. Best Time to Buy and Sell Stock II
2018-01-05 13:34
281 查看
问题
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).
2.描述
代码
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).
2.描述
这道题着实把我坑到了,先描述一下题意就是给定一个数组,数组是每天股票的价格,需要确定最大的收益是多少,一开始思想我就直接搞成排序了,哈哈找到最大值与最小值的查 -。- 后来改成寻找每个数字的下一个大的值,放进Map,然后根据遍历数组,找到低买高出整条线路,然后比较全部线路的最大收益。比较麻烦!! 后续改为只要从头开始进行判断然后比较下一个值如果下一个值较大则前一个值买入,最大值卖出,然后进行依次递进。
代码
class Solution { public int maxProfit(int[] prices) { int res = 0; for (int i = 0; i < prices.length - 1; ++i) { if (prices[i] < prices[i + 1]) { res += prices[i + 1] - prices[i]; } } return res; } }
相关文章推荐
- [Leetcode 122, Medium] Best Time to Buy and Sell Stock II
- Medium 122题 Best Time to Buy and Sell Stock II
- leetcode[122]Best Time to Buy and Sell Stock II
- 122. Best Time to Buy and Sell Stock II
- 122. Best Time to Buy and Sell Stock II
- 122. Best Time to Buy and Sell Stock II
- leetcode_[python/C++]_121/122/123/188.Best Time to Buy and Sell Stock I/II/III/IV
- 122. Best Time to Buy and Sell Stock II
- LeetCode 122 Best Time to Buy and Sell Stock II
- Lettcode_122_Best Time to Buy and Sell Stock II
- LeetCode 122 -- Best Time to Buy and Sell Stock II
- 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
- leetcode122 Best Time to Buy and Sell Stock II
- 122. Best Time to Buy and Sell Stock II
- 【leetcode 122】javascript 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 问题 in JAVA
- 122. Best Time to Buy and Sell Stock II