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 (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

最新文章

  1. 邓博泽 java最全的DateUtil工具类
  2. 在MVC3中使用code first生成数据局库并操作数据库
  3. 用Myeclipse 编写struts.xml时,自动提示
  4. Ubuntu 16.04 LTS 正式发布:系统将持续更新5年
  5. PopupWindow的基本使用
  6. C# .NET更智能的数据库操作的封装
  7. Python自动生产表情包
  8. J2EE 项目本地发布路径及修改
  9. FileSync文件同步更新工具
  10. !!!常用SVG代码
  11. noip第20课资料
  12. FastAdmin 开发学习给输入框加上清除功能
  13. MongoDB的常规备份策略
  14. 【BZOJ1047】[HAOI2007]理想的正方形(单调队列,动态规划)
  15. C语言open()函数:打开文件函数(转)
  16. codeforces水题100道 第十五题 Codeforces Round #262 (Div. 2) A. Vasya and Socks (brute force)
  17. PCB常见的拓扑结构 (转)
  18. 使用ie的filter来解决rgba在IE8下没有效果的问题
  19. PAT 1056 Mice and Rice[难][不理解]
  20. MySQL 8.0.2复制新特性(翻译)

热门文章

  1. rabbitmq-5-案例2-简单的案例+exchange
  2. send csv to es with filebeat
  3. 前端学习(二十二)css3(笔记)
  4. excel acm 高校排名(hdoj)
  5. leetcode-166周赛-5280-用户分组
  6. linux shell的单行多行注释
  7. 【LeetCode 30】串联所有单词的子串
  8. 基于jquery和bootstrap的下拉框左右选择功能
  9. MySql插入数据成功但是报[Err] 1055
  10. 根据一个经纬度坐标获取周边最近经纬。Java实现