博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Best Time to Buy and Sell Stock
阅读量:7014 次
发布时间:2019-06-28

本文共 643 字,大约阅读时间需要 2 分钟。

shares a very simple solution, whose code is rewritten below, just 5 lines :-)

1 class Solution { 2 public: 3     int maxProfit(vector
& prices) { 4 int low = INT_MAX, profit = 0; 5 for (int price : prices) { 6 low = min(low, price); 7 profit = max(profit, price - low); 8 } 9 return profit;10 }11 };

To give an explanation, suppose we denote p[n] to be the maximum profit we can earn from days 0 to n. Then we have the following DP recursive formula:

p[n + 1] = max(p[n], prices[n + 1] - min_{i = 0, ..., n}prices[i]).

The above code simply computes this formula :-)

转载地址:http://uphtl.baihongyu.com/

你可能感兴趣的文章
H.264 CODEC
查看>>
计算机图形学中的经常使用模型
查看>>
Android生成keystore是报错拒绝访问
查看>>
JSP如何在servlet将一个数据模型对象传递给jsp页面
查看>>
PHP 实现“贴吧神兽”验证码
查看>>
根据一个表的数据情况显示另一个表的数据
查看>>
Python中的类
查看>>
【摘】请问make -j8 和make -j4 是什么意思?什么作用?
查看>>
iOS 10 的适配问题-b
查看>>
linux设备驱动编写_tasklet机制
查看>>
Mysql客户端中文乱码问题解决
查看>>
分布式搜索Elasticsearch——QueryBuilders.matchPhrasePrefixQuery
查看>>
课程2:《黑马程序员_Java基础视频-深入浅出精华版》-视频列表-
查看>>
TP4056大电流1A使用注意事项
查看>>
java代理模式之静态代理
查看>>
ASP.NET MVC5+EF6+EasyUI 后台管理系统(80)-自由桌面
查看>>
Java常考面试题(四)
查看>>
前端学数据库之记录操作
查看>>
学习Javascript闭包(Closure)
查看>>
【Todo】git的fast forward & git命令学习 & no-ff
查看>>