【Leetcode】Best Time to Buy and Sell Stock
2016-06-01 20:08
351 查看
题目链接:https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
题目:
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 (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
思路:
当前元素的最大收益只跟前面最小元素有关。
算法:
public int maxProfit(int[] prices) {
int maxProfit = 0;
int minEle = Integer.MAX_VALUE;
for (int i = 0; i < prices.length; i++) {
maxProfit = Math.max(maxProfit, prices[i]-minEle);
minEle = Math.min(minEle, prices[i]);
}
return maxProfit;
}
题目:
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 (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
思路:
当前元素的最大收益只跟前面最小元素有关。
算法:
public int maxProfit(int[] prices) {
int maxProfit = 0;
int minEle = Integer.MAX_VALUE;
for (int i = 0; i < prices.length; i++) {
maxProfit = Math.max(maxProfit, prices[i]-minEle);
minEle = Math.min(minEle, prices[i]);
}
return maxProfit;
}
相关文章推荐
- JSP 实用程序之简易图片验证码
- HashTable二次探测
- 【Leetcode】Count and Say
- ECC
- TCP管理的4种定时器
- ActiveMQ 的安装(单节点)
- {算法}YY矩阵乘法
- 彻底理解:阻塞、非阻塞、同步、异步、Reactor、Proactor
- UVA - 11991 Easy Problem from Rujia Liu?【STL】
- POJ 1061 青蛙的约会(扩展欧几里得算法)
- Semaphore示例
- Kafka Topic Partition Replica Assignment实现原理及资源隔离方案
- 更新UI 2种方法
- zzulioj1873: This offer 深搜
- 每日scrum(4)
- [转]定位占用oracle数据库cpu过高的sql
- LeetCode-347.Top K Frequent Elements
- 图片下载
- Linux的文件权限
- Flume 数据采集系统 性能优化和关键问题汇总