题目描述
思路
1.暴力法(O(N^2))
对每一个值,找后面的最大差值
class Solution {
public int maxProfit(int[] prices) {
//暴力法
if(prices == null || prices.length == 0){
return 0;
}
int res = 0;
for(int i = 0; i < prices.length-1;i++){
int temp = 0;
for(int j = i+1; j < prices.length;j++){
if(prices[j] > prices[i] && prices[j]-prices[i] > temp){
temp = prices[j] - prices[i];
res = temp > res ? temp : res;
}
}
}
return res;
}
}
2.利用最低“谷”,一次遍历O(n)
我们维护一个minPrice 的变量,如果遍历到的数字比这个变量小,更新这个变量。
否则,看看 prices[i] - minPrice 的值是否比我们之前得到的 maxProfit 要大,如果大,就更新;否则,不更新。
class Solution {
public int maxProfit(int[] prices) {
//一次遍历
if(prices == null || prices.length == 0){
return 0;
}
int minPrice = Integer.MAX_VALUE;
int maxProfit = 0;
for(int i = 0; i < prices.length ;i++){
if(prices[i] < minPrice){
minPrice = prices[i];
}else if(prices[i] - minPrice > maxProfit){
maxProfit = prices[i] - minPrice;
}
}
return maxProfit;
}
}
3.通用方法解决股票问题
public int maxProfit(int[] prices) {
if(prices == null || prices.length == 0){
return 0;
}
int n = prices.length;
int[][] dp = new int[n][2];
for(int i = 0; i < n;i++){
if(i-1 == -1){
dp[i][0] = 0;
dp[i][1] = -prices[i];
continue;
}
dp[i][0] = Math.max(dp[i-1][0],dp[i-1][1]+prices[i]);
dp[i][1] = Math.max(dp[i-1][1],-prices[i]);
}
return dp[n-1][0];
}
空间复杂度降到O(1)
public int maxProfit(int[] prices) {
if(prices == null || prices.length == 0){
return 0;
}
int n = prices.length;
int dp_i_0 = 0;
int dp_i_1 = Integer.MIN_VALUE;
for(int i = 0 ; i < n;i++){
dp_i_0 = Math.max(dp_i_0,dp_i_1+prices[i]);
dp_i_1 = Math.max(dp_i_1,-prices[i]);
}
return dp_i_0;
}