题目:假设把某股票的价格按照时间先后顺序存储在数组中,请问买卖该股票一次可能获得的最大利润是多少?
思路;这道题目使用动态规划做,第一次看题的时候一直在想什么时候买,什么时候卖,题目要求是要利润最大,因此直接在价格i天前最低的时候买就行,接下来就是计算每一个卖出的利润(当天的价格减去前面最低的价格)。
//股票最大利润
class Solution {
public int maxProfit(int[] prices) {
//动态规划,初试值,dp[0] = 0;
//状态转移方程 dp[i] = Math.max(dp[i-1],当前天的利润(当天的价格-前面几天最低的价格));
int profit = 0;//相当于dp[0]=0
int cost = Integer.MAX_VALUE;
for(int i=0;i<prices.length;i++){//从0开始,找出前i天最低的价格
cost = Math.min(cost,prices[i]);
profit = Math.max(profit,prices[i] - cost);
}
return profit;
}
}