class Solution {
public int maxProfit(int[] prices) {
//暴力求解,从后往前找每一个数对应前面的数的差,O(N*N),遇到很长的数据会超时
int res = 0;
for(int i = prices.length - 1; i >= 0; i--){
for(int j = i - 1; j >= 0; j--){
if(prices[i] - prices[j] > res){
res = prices[i] - prices[j];
}
}
}
return res;
}
}
class Solution {
public int maxProfit(int[] prices) {
//因为要寻找最大利益,这就说明了有一个比较更新res的过程,DP
//上一种解法是暴力比较,会超时,下面这种解法只用一个循环,比较过程中更新big是一个关键
//寻找最大利益需要出售价尽可能高,进价尽可能高,而进价是在往前找,所以更新出售价big的值
if(prices.length == 0) return 0;
int res = 0;
int big = prices[prices.length - 1];
for(int i = prices.length - 2; i >= 0; i--){
if(big - prices[i] > res){//从后往前比较过程中更新最大利益的值
res = big - prices[i];
}
if(prices[i] > big){//从后往前比较过程中也更新出售价big的值
big = prices[i];
}
}
return res;
}
}
leetcode [Best Time to Buy and Sell Stock]//待整理多种解法
class Solution { public int maxProfit(int[] prices) { //暴力求解,从后往前找每一个数对应前面的数的差,O(N*N),遇到很长的数据会超时 int res = 0; for(int i = prices.length - 1; i >= 0; i--){ for(int j =