笔试遇到好几次。
方法一:类似于动态规划?暴力法,递归层级计算最优解
public int calculate(int prices[], int s) {
if (s >= prices.length)
return 0;
int max = 0;
for (int start = s; start < prices.length; start++) {
int maxprofit = 0;
for (int i = start + 1; i < prices.length; i++) {
if (prices[start] < prices[i]) {
int profit = calculate(prices, i + 1) + prices[i] - prices[start];
if (profit > maxprofit)
maxprofit = profit;
}
}
if (maxprofit > max)
max = maxprofit;
}
return max;
}
}
方法二:数学分析
寻找递增的序列,并让峰值和谷值进行相减。
class Solution {
public int maxProfit(int[] prices) {
if(prices.length==0||prices==null)
return 0;
return cal(prices, 0);
}
public int cal(int prices[],int s){
int len=prices.length;
int j=0;
int count=0;
for(int i=1;i<len;i++){
if(prices[i]>=prices[i-1]){
continue;
}
count+=(prices[i-1]-prices[j]);
j=i;
}
if(j!=len-1){
count+=(prices[len-1]-prices[j]);
}
return count;
}
}