Best Time to Buy and Sell Stock
来源:互联网 发布:学日语软件樱花 编辑:程序博客网 时间:2024/06/10 04:27
题意:
N天之内只能交易一次。
思路:
(最初想法)要想在第N天获得最大利益,那么股票需要在第k(k<=N)天出售,那就需要知道前k天中哪天的价格最低,k遍历第1至N天,最大差值即为所求。
(改进想法)从第N至1天遍历,每次比较p[i]得出最大值Max,这样遍历到第i天(该天购买股票)时,就知道第i至N天最大股票价格Max,(Max - p[i])为第i天购买股票获取的最大利益。第1-N天中最大利益即为所求。
import java.util.Arrays;import java.util.HashMap;public class Solution { public int maxProfit(int[] p) { if(p.length == 0)return 0; int Max = p[p.length-1]; int res = 0; for(int i=p.length-1;i>=0;i--){ Max = Math.max(Max, p[i]); res = Math.max(res, Max - p[i]); } return res; }}
0 0
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time To Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- 解码器寄存器控制
- POJ 1904 Brainman(归并求逆序数)
- DevStack安装问题,git clone noVNC.git失败
- UITabbarController的高度调整和背景图片的添加
- maven+springjpa+hibernate
- Best Time to Buy and Sell Stock
- 文搏实业 生产、销售一体化
- 对象访问
- sharepoint 设置webpart 直接空隙
- jackson的一个异常
- html中 <a href> 和<img src>的用法
- LeetCode之旅(15)
- 经典收藏 50个jQuery Mobile开发技巧集萃
- Android Home键监听