LeetCode 121 Best Time to Buy and Sell Stock
2016-04-11 23:28
435 查看
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.
假设有一个数组,它的第i个元素是一支给定的股票在第i天的价格。如果你最多只允许完成一次交易(例如,一次买卖股票),设计一个算法来找出最大利润。
给出一个数组样例[3,2,3,1,2], 返回 1。
此题目为dp(动态规划)问题。第i天卖出的最大收益即为第i天的股市价格减去[0,i-1]天内的最小股市价格,如果这个值大于当前最大利润值,就更新当前最大利润值。当第i天的股市价格比[0,i-1]天内最低股市价格还低,则更新最低股市价格。
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.
假设有一个数组,它的第i个元素是一支给定的股票在第i天的价格。如果你最多只允许完成一次交易(例如,一次买卖股票),设计一个算法来找出最大利润。
给出一个数组样例[3,2,3,1,2], 返回 1。
此题目为dp(动态规划)问题。第i天卖出的最大收益即为第i天的股市价格减去[0,i-1]天内的最小股市价格,如果这个值大于当前最大利润值,就更新当前最大利润值。当第i天的股市价格比[0,i-1]天内最低股市价格还低,则更新最低股市价格。
public int maxProfit(int[] prices) { if (prices.length == 0) return 0; int minbuy = prices[0], profit = 0; for (int i = 1; i < prices.length; i++) { minbuy = Math.min(prices[i], minbuy); profit = Math.max(profit, prices[i] - minbuy); } return profit; }
相关文章推荐
- C++第二次作业2
- 爆打团队 2016.04.11 站立会议
- vs开启/禁用随机基址
- 使用unittest.TestSuite组织执行用例
- leetcode
- div展现与收起效果(鼠标移入移出)
- Python sort dict by value
- c++实验3-个人所得税计算器
- 通过yum安装
- Hadoop MapReduce InputFormat基础
- Light oj 1197 - Help Hanzo
- c语言 之求 Fibionacci 数列的前n个数
- block为什么用copy
- 简单的mvc 框架(二)
- 随便写写20160411
- Microsoft Azure Host OS&Guest OS
- 02-git删除文件
- Simulating queueing systems with simmer
- HTML标签marquee实现滚动效果
- 36.微改进的计算器,JComboBox下拉框