【DP&数组】Best Time to Buy and Sell Stock
来源:互联网 发布:绿色上网软件手机软件 编辑:程序博客网 时间:2024/05/18 00:35
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.
题意:股票最多买一次、卖一次解法:遍历数组,固定住当前最小值,以后的元素若是大于它则重设利润值max,否则重设最小值index
public class Solution { public int maxProfit(int[] prices) { if(prices == null || prices.length==0) return 0; int min = 0; int max = 0; for(int i=1; i<prices.length; i++){ if(prices[i] > prices[min]){ max = Math.max(max, prices[i]-prices[min]); } else min = i; } return max; }}
解法二:将数组中prices[i+1]-prices[i]建立一个新数组,可以将问题转化成求数组的最大连续子数组和
子段和= prices[j]-prices[j-1]+prices[j-1]-prices[j-2]+...+prices[i]-prices[i-1] = prices[j]-prices[i-1], 即prices[j]是最大价格,prices[i-1]是最小价格,且他们满足前后顺序关系
public class Solution { public int maxProfit(int[] prices) { if(prices == null || prices.length==0 || prices.length==1) return 0; int sum = 0, curSum = 0; for(int i=1; i<prices.length; i++){ if(curSum > 0) curSum += prices[i] - prices[i-1]; else curSum = prices[i] - prices[i-1]; sum = Math.max(curSum ,sum); } return sum; }}
0 0
- 【DP&数组】Best Time to Buy and Sell Stock
- 【数组&DP】Best Time to Buy and Sell Stock III
- [LeetCode] [Python] [DP] Best Time to Buy and Sell Stock
- 【Leetcode】Best Time to Buy and Sell Stock (DP)
- 【Leetcode】Best Time to Buy and Sell Stock III (DP)
- [leetcode][DP] Best Time to Buy and Sell Stock
- [leetcode][DP] Best Time to Buy and Sell Stock III
- [leetcode][DP] Best Time to Buy and Sell Stock
- [leetcode][DP] Best Time to Buy and Sell Stock III
- LeetCode Best Time to Buy and Sell Stock(dp)
- LeetCode Best Time to Buy and Sell Stock III(dp)
- leetcode121.[DP]Best Time to Buy and Sell Stock
- leetcode122.[DP] Best Time to Buy and Sell Stock II
- leetcode123. [DP]Best Time to Buy and Sell Stock III
- DP---Best Time to Buy and Sell Stock
- DP——Best Time to Buy and Sell Stock
- 121. Best Time to Buy and Sell Stock (dp)
- 【数组】Best Time to Buy and Sell Stock II
- MyBatis学习 之 一、MyBatis简介与配置MyBatis+Spring+MySql
- 2010-02-04 11:55 图片与文字垂直居中
- MyBatis学习 之 二、SQL语句映射文件(1)resultMap
- 区域生长opencv2下的实现
- 扩展欧几里德定理
- 【DP&数组】Best Time to Buy and Sell Stock
- 指针传递
- 使用Struts2开发Java Web应用程序(目录)
- vs2012使用命令行编译的设置
- Github error – fatal: Unable to look up github.com (port 9418) (Name or service not known)
- RT-Thread基础一
- 快速排序算法
- STM32F4 串口程序 调试记录 hardfault_handle 问题
- 优化Python程序性能的15个小技巧