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.
exp:
[2,1,4] output:3
[2,1,4,1,7] output:6
典型的dp题目.上代码了
public class Solution {
public int maxProfit(int[] prices) {
if(prices.length<2) return 0;
int n = prices.length;
int[] ret = new int[n];
ret[0] = 0;
int buy = prices[0];
int max = 0;
for(int i=1;i<n;i++){
if(prices[i]<=buy){
buy = prices[i];
ret[i] = ret[i-1];
}
else {
if(prices[i]-buy > max){
ret[i] = prices[i] - buy;
max = ret[i];
}else{
ret[i]=ret[i-1];
}
}
}
return ret[n-1];
}
}