leetcode——Best Time to Buy and Sell Stock
来源:互联网 发布:中冶南方自动化知乎 编辑:程序博客网 时间:2024/06/06 20:58
题目:
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.
思路:
题目中要求,买卖只能有一次,而且必须先买后卖。
因此,该题跟求最大子串和很类似。需要辅助数组p[],标记如果i位置上卖出所能得到的最大收益。
因此,p[0]=0.
若price[i+1]-price[i]>0,则p[i+1] = p[i]+price[i+1]-price[i];
否则,p[i+1]=0;
这就是转换方程。在计算p的同时,记录max。
AC代码:
public int maxProfit(int[] prices) { if(prices==null || prices.length==0) return 0; int [] p = new int[prices.length]; p[0] = 0; int max = 0; for(int i=1;i<prices.length;i++){ if(p[i-1]+prices[i]-prices[i-1]>=0){ p[i] = p[i-1]+prices[i]-prices[i-1]; } else{ p[i] = 0; } max = max>p[i]?max:p[i]; } return max; }
0 0
- Leetcode —— Best Time to Buy and Sell Stock
- LeetCode——Best Time to Buy and Sell Stock
- LeetCode——Best Time to Buy and Sell Stock
- 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——Best Time to Buy and Sell Stock
- LeetCode—Best Time to Buy and Sell Stock
- 【LeetCode】Best Time to Buy and Sell Stock & Best Time to Buy and Sell Stock
- DP——Best Time to Buy and Sell Stock
- Algorithms—121.Best Time to Buy and Sell Stock
- LeetCode121—Best Time to Buy and Sell Stock
- LeetCode122—Best Time to Buy and Sell Stock II
- LeetCode123—Best Time to Buy and Sell Stock III
- LeetCode188—Best Time to Buy and Sell Stock IV
- Leetcde——121 Best Time to Buy and Sell Stock && 123 Best Time to Buy and Sell Stock
- [LeetCode] [LeetCode]Best Time to Buy and Sell Stock
- leetcode——309——Best Time to Buy and Sell Stock with Cooldown
- Java回调函数的理解
- python实现中文字符繁体和简体中文转换
- perl split函数
- 关于工程优化方面
- Android的四种点击事件
- leetcode——Best Time to Buy and Sell Stock
- addEventListener,addNodeEventListener解释
- 在Eclipse中使用JUnit4进行单元测试(3)
- android音量设置from top to bottom
- 基于协同过滤算法推荐的过程
- 使用GDB命令行调试器调试C/C++程序
- EL表达式的学习(一)—————EL自定义函数的使用
- MySQL导入数据库文件过大报错
- 将控制台输入的字符串连接成一个长的字符串,并以";"作分割符