二刷
import java.util.*;
public class Solution {
/**
*
* @param prices int整型一维数组
* @return int整型
*/
public int maxProfit (int[] prices) {
int min = prices[0];
int max = 0;
for(int num:prices){
max = Math.max(max,num - min);
min = Math.min(min,num);
}
return max;
}
}import java.util.*;
public class Solution {
/**
*
* @param prices int整型一维数组
* @return int整型
*/
public int maxProfit (int[] prices) {
if(prices.length < 2) return 0;
int[][] dp = new int[prices.length][prices.length];
int max = 0;
for(int i=0; i<prices.length; i++ ){
for(int j = i+1; j<prices.length; j++){
dp[i][j] = prices[j]-prices[i];
max = Math.max(dp[i][j],max);
}
}
return max;
}
}其实一次遍历就还保存之前的最小值 和 最大利润。



京公网安备 11010502036488号