Leetcode-best-time-to-buy-and-sell-stock
来源:互联网 发布:深圳淘宝培训班免费 编辑:程序博客网 时间:2024/06/06 04:15
题目描述
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.
只允许做一次交易,则找出最高股价-最低股价。
动态规划问题:dp[i]表示第i天的收益,则等于prices[i]-min(prices[0...i-1]),即第i天的股价减去前i-1天的最低股价,如果第i天的股价比前i-1天的最低股价还要低,则更新最小值,供后续计算使用,思路很清晰了,下面就是代码。
public class Solution { public int maxProfit(int[] prices) { int n = prices.length; if(n == 0) return 0; int maxpro = 0; int min = prices[0]; for(int i=1; i<n; i++){ min = Math.min(prices[i], min); //比较第i天的股价和前i-1天的最低价,取最小值 if(prices[i] - min > maxpro) maxpro = prices[i] - min; //maxpro表示第i天的收益,就是第i天的股价减去前i-1天的最低价 } return maxpro; }}
0 0
- 【LeetCode】Best Time to Buy and Sell Stock & Best Time to Buy and Sell Stock
- [LeetCode] [LeetCode]Best Time to Buy and Sell Stock
- 【LeetCode with Python】 Best Time to Buy and Sell Stock
- [LeetCode]Best Time to Buy and Sell Stock
- [LeetCode]Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock
- LeetCode Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock III
- Leetcode: Best time to buy and sell a stock I
- Leetcode: Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock III
- [Leetcode] Best Time to Buy and Sell Stock
- [Leetcode] Best Time to Buy and Sell Stock II
- [Leetcode] Best Time to Buy and Sell Stock III
- LeetCode : Best Time to Buy and Sell Stock II
- [leetcode] Best Time to Buy and Sell Stock
- leetcode 16: Best Time to Buy and Sell Stock III
- LeetCode Best Time to Buy and Sell Stock
- git简单操作
- Baas服务平台有哪些?应用开发有哪些第三方服务
- iOS容易造成循环引用的三种场景,就在你我身边!
- Libxml2 2.9.4 编译失败 error C2275 处理方法
- 青蛙的烦恼
- Leetcode-best-time-to-buy-and-sell-stock
- Java实现字符串转换成可执行代码
- Heroku 安装教程
- Where to put “-p” for solving “pptpd is not running”?
- Android事件分发机制
- 代理模式与装饰模式的异同
- Android5.0 MediaSession框架
- hibernate有哪些状态?
- mongodb全量备份,简单的实现方式