121. Best Time to Buy and Sell Stock
来源:互联网 发布:销售知乎 编辑:程序博客网 时间:2024/04/29 11:31
https://leetcode.com/problems/best-time-to-buy-and-sell-stock/#/description
股票买入和卖出的最大差价,只允许交易一次,实际上就是计算数组中靠后的值和靠前的值最大差。
public class Solution {
public int maxProfit(int[] prices) {
int profit = 0;
if(prices.length == 0)
return 0;
int low = prices[0];
for(int i = 1;i < prices.length;i ++){
if(prices[i] < low){
low = prices[i];
}
else if(prices[i] - low > profit){
profit = prices[i] - low;
}
}
return profit;
}
}
看了一下讨论区,题目可以变形成,如果input是前后两个数字的差,比如输入由{1, 7, 4, 11}变成{0, 6, -3, 7},这道题就转换成maximum subarray(第53题).
逻辑上,题目的思路就变成了,求由前后两个数字差形成的新数组的最大子数列和。如果这个和小于0,则返回0.
public int maxProfit(int[] prices) { int maxCur = 0, maxSoFar = 0; for(int i = 1; i < prices.length; i++) { maxCur = Math.max(0, maxCur += prices[i] - prices[i-1]); maxSoFar = Math.max(maxCur, maxSoFar); } return maxSoFar; }
maxCur:最大值;maxSoFar:当前最大值
- 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
- Oracle建立表空间和用户
- 欢迎使用CSDN-markdown编辑器
- 阿里云提示 Didcuz memcache+ssrf GETSHELL漏洞修复方法
- lambda表达式
- 金明的预算方案 01背包变形
- 121. Best Time to Buy and Sell Stock
- 金融保险中的几个概念
- Websocket
- oracle中的表空间
- Android 自定义View
- 一个TextView 显示多种样式的文本
- FreeRTOS中的堆栈设置”与“系统启动文件中堆栈”的关系
- C#索引器
- 二叉搜索树的插入,删除,遍历操作详解