题目:假设把某股票的价格按照时间先后顺序存储在数组中,请问买卖该股票一次可能获得的最大利润是多少?
解法一:暴力解法
两层循环,对于每一个数,都去计算它与前面的数差的最大值。
public int maxProfit(int[] prices) {
if(prices.length==0)return 0;
int max_Profit=0;
int price = 0;
for(int i=1;i<prices.length;i++){
for(int j=0;j<i;j++){
price = prices[i]-prices[j];
max_Profit = max_Profit>price?max_Profit:price;
}
}
return max_Profit;
}
解法二:维护最小值法
设置一个变量,表示最小值,遍历数组,把当前数与最小值判断,比它小就把它赋给最小值,否则,就用它与最小值求差,找出最大的。
public int maxProfit1(int[] prices) {
if (prices.length==0||prices==null)return 0;
int min = prices[0];
int res = 0;
for (int i=1;i<prices.length;i++){
if (prices[i] <min){
min = prices[i];
}else {
res = Math.max(res,prices[i]-min);
}
}
return res;
}
解法三:动规解法
public static int maxProfit2(int[] prices) {
if (prices.length==0||prices==null)return 0;
int max = 0;
int n = prices.length;
int[] dp = new int[n];
dp[1] = prices[1]-prices[0];
max = Math.max(dp[1],max);
for (int i=2;i<n;i++){
int j = i-1;
if(dp[j]>0){
dp[i] = prices[i]-prices[j]+dp[j];
}else {
dp[i] = prices[i]-prices[j];
}
max = Math.max(max,dp[i]);
}
return max;
}