问题

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/4014 访问。

给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。

如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。

注意你不能在买入股票前卖出股票。

输入: [7,1,5,3,6,4]

输出: 5

解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。

输入: [7,6,4,3,1]

输出: 0

解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。


Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

Input: [7,1,5,3,6,4]

Output: 5

Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.Not 7-1 = 6, as selling price needs to be larger than buying price.

Input: [7,6,4,3,1]

Output: 0

Explanation: In this case, no transaction is done, i.e. max profit = 0.


示例

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/4014 访问。

public class Program {

    public static void Main(string[] args) {
int[] prices = { 7, 1, 5, 3, 6, 4 }; var res = MaxProfit(prices);
Console.WriteLine(res); Console.ReadKey();
} private static int MaxProfit(int[] prices) {
int result = 0;
if(prices == null || prices.Length == 0)
return 0;
int min = prices[0];
for(int i = 1; i < prices.Length; i++) {
//动态规划
result = Math.Max(result, prices[i] - min);
min = Math.Min(min, prices[i]);
}
return result;
} }

以上给出1种算法实现,以下是这个案例的输出结果:

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/4014 访问。

5

分析:

在最坏的情况下,以上算法的时间复杂度为:  。

最新文章

  1. Git Shell 基本命令(官网脱水版)
  2. Light OJ 1140
  3. hdu2191 悼念512汶川大地震 ——多重背包
  4. 搭建DHCP服务器以及DHCP中继服务器
  5. 实现毛玻璃模糊效果/DRNRealTimeBlur
  6. OC基础--OC中的类方法和对象方法
  7. hdu1828(线段树+扫描线)
  8. Dialog控件
  9. ExtJs自学教程(1):一切从API開始
  10. Codeforces 235E Number Challenge
  11. python网络编程——将IPv4地址转换成不同的格式
  12. Effective C++_笔记_条款07_为多态基类声明virtual析构函数
  13. 4种Delphi IDE的调试时查看内存的方法,太酷了!
  14. 简单介绍移动端CSS3单位rem的用法
  15. Swing使用JavaFXweb组件
  16. Python:鲜为人知的功能特性(下)
  17. java类加载及类初始化
  18. Buffer cache hit ratio性能计数器真的可以作为SQL Server 内存瓶颈的判断指标吗?
  19. 深入了解preventDefault与stopPropagation
  20. CLR基础,CLR运行过程,使用dos命令创建、编译、运行C#文件,查看IL代码

热门文章

  1. C++算法 广搜
  2. LGTB 与 序列
  3. xenomai内核解析之信号signal(二)---xenomai信号处理机制
  4. React native项目后期调整UI总结
  5. 面试题四十:数组中最小的k个数
  6. 基于jqgrid + ashx + nhibernate的分页
  7. shell变量子串
  8. SpringBoot整合Mail发送邮件&amp;发送模板邮件
  9. 配置mongoDB的错误
  10. 线程_Process基础语法