leetcode Best Time to Buy and Sell Stock
题目
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做。
一开始把题目想复杂了,后来发现还是挺简单的,有很多类似的题目,下面给出思路。
设置一个值currentMax,该值记录a[0]-a[k]内,在0-k内买入,k卖出的最大值。
那么currentMax[i+1]=
if(currentMax[i]>0)
currentMax[i]+(a[i+1]-a[i])
else
a[i+1]-a[i]
比如,对于6,1,3,2,4,7
对于6,1,买入卖出肯定是亏损的,此时的max为-5
那么对于6,1,3来说,6,1最大值是负的,那么6,1,3的最大值肯定不包含6,1.因此其最大值为2
对于6,1,3,2,来说,6,3,1的最大值为2,那么最大值为1
依次类推
下面给出代码
public class Solution { /** * @param args */ public int maxProfit(int[] prices) { if(prices.length==0||prices.length==1) return 0; int maxEnd=1; int currentMax=0; int max=0; for(int i=1;i<prices.length;i++) { System.out.println("i="+i+",maxEnd="+maxEnd+"max="+max); if(currentMax>0) { currentMax=prices[i]-prices[i-1]+currentMax; } else { currentMax=prices[i]-prices[i-1]; } if(currentMax>max) max=currentMax; } if(max<0) return 0; return max; } public static void main(String[] args) { // TODO Auto-generated method stub int []a={6,1,3,2,4,7}; System.out.println(new Solution().maxProfit(a)); } }