LeetCode Array Easy 122. Best Time to Buy and Sell Stock II
2024-08-31 17:48:32
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).
Example 1:
Input: [,,,,,]
Output:
Explanation: Buy on day (price = ) and sell on day (price = ), profit = - = .
Then buy on day (price = ) and sell on day (price = ), profit = - = .Example 2:
Input: [,,,,]
Output:
Explanation: Buy on day (price = ) and sell on day (price = ), profit = - = .
Note that you cannot buy on day , buy on day and sell them later, as you are
engaging multiple transactions at the same time. You must sell before buying again.Example 3:
Input: [,,,,]
Output:
Explanation: In this case, no transaction is done, i.e. max profit = .
问题描述: 给定一个数组,每一位代表当前索引的价格。设计一个算法,计算出最大利润。可以多次买卖。但是买卖不能在同一天操作
思路:这一题用到了贪心的思想。通过获取局部局部最优来达到整体最优解。找到递减区间的最低点,及最后一个点,同时再找到递增区间的最高点,也是最后一个点。把他们的差值累加,获得最大利润
public static int MaxProfit2(int[] prices)
{
int len = prices.Length;
int total = ;
int i = ;
while(i < len - )
{
int sell =, buy = ;
while (i + < len && prices[i + ] < prices[i])//获取递减区最低点(局部最小)
i++;
buy = i;//将最小点作为买入点
i++;//找下一个点,卖出点至少是买入点的下一个点
while (i < len && prices[i] > prices[i - ])//获取递增区最高点(局部最大)
i++;
sell = i - ;//获取卖出点
total += prices[sell] - prices[buy];
}
return total;
}
想法来源: https://www.cnblogs.com/grandyang/p/4280803.html
最新文章
- 邓博泽 java最全的DateUtil工具类
- 在MVC3中使用code first生成数据局库并操作数据库
- 用Myeclipse 编写struts.xml时,自动提示
- Ubuntu 16.04 LTS 正式发布:系统将持续更新5年
- PopupWindow的基本使用
- C# .NET更智能的数据库操作的封装
- Python自动生产表情包
- J2EE 项目本地发布路径及修改
- FileSync文件同步更新工具
- !!!常用SVG代码
- noip第20课资料
- FastAdmin 开发学习给输入框加上清除功能
- MongoDB的常规备份策略
- 【BZOJ1047】[HAOI2007]理想的正方形(单调队列,动态规划)
- C语言open()函数:打开文件函数(转)
- codeforces水题100道 第十五题 Codeforces Round #262 (Div. 2) A. Vasya and Socks (brute force)
- PCB常见的拓扑结构 (转)
- 使用ie的filter来解决rgba在IE8下没有效果的问题
- PAT 1056 Mice and Rice[难][不理解]
- MySQL 8.0.2复制新特性(翻译)