Best Time to Buy and Sell Stock
来源:互联网 发布:mac无线鼠标没反应 编辑:程序博客网 时间:2024/06/03 17:05
一道很好的题,career cup上有一道facebook的题和这个一模一样: Given an array, find the maximum difference between two array elements given the second element comes after the first.
解法是保存数组中发现的最小值,每发现当前的值比最小值大,再看这个差值和diff谁大,保存最大的diff,继续移动。所以这是一个O(N)的算法。O(N*N)的算法是所有的的元素都做减法,保留最大的diff,就不写了。
public int maxProfit(int[] prices) { int diff = 0; int minV = Integer.MAX_VALUE; for (int i = 0; i < prices.length; i++){ if(prices[i] < minV) minV = prices[i]; if(prices[i] > minV) { diff = Math.max(prices[i] - minV, diff); } } return diff; }
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
- Windows Server 2008 R2搭建域环境中遇到的一个小错误
- LeetCode - Single number- Jan 31, 2015
- 升域的时候出现“安装Active Directory 域服务二进制文件失败”的解决办法
- Windows Server 2008 Active Directory域服务安装
- VC显示网页验证码、模拟CSDN网页登录
- Best Time to Buy and Sell Stock
- ecshop 商品详情页面显示-赠品信息-优惠活动
- mysql学习笔记-服务器端程序
- Android 4.4 的权限问题,导致App 裁剪图片不能保存(已解决)
- install matlab iso on ubuntu
- Best Time to Buy and Sell Stock II
- muduo代码阅读笔记及注释
- ativity 传值
- API