题目描述1
笔者解答1.1
class Solution {
public int maxProfit(int[] prices) {
if(prices.length<=1)return 0;
int[] max=new int[1];
Mergesort(0,prices.length-1,prices,max);
return max[0]>0?max[0]:0;
}
public static void Mergesort(int start,int end,int[] prices,int[] max)
{
int result=0;
if(start==end)return;
else{
int mid=(start+end)/2;
Mergesort(start,mid,prices,max);
Mergesort(mid+1,end,prices,max);
result=prices[end]-prices[start];
if(result>max[0])max[0]=result;
int i=start;
int j=mid+1;
int[] temp=new int[end-start+1];
int temp_index=0;
while(i<=mid&&j<=end){
if(prices[i]<prices[j]){
temp[temp_index]=prices[i];
temp_index++;
i++;
}else{
temp[temp_index]=prices[j];
temp_index++;
j++;
}
}
if(i!=mid+1){
for(;i<=mid;i++){
temp[temp_index]=prices[i];
temp_index++;
}
}
if(j!=end+1){
for(;j<=end;j++){
temp[temp_index]=prices[j];
temp_index++;
}
}
for(i=0;i<end-start+1;i++){
prices[start+i]=temp[i];
}
}
}
}
笔者分析1.2
挺有意思的一道题,因为昨天花了些精力总结了归并排序的应用,所以这次特意用归并排序写了,执行时间超过百分之60,还是挺满意的(用归并,是一下子没有想到其他好的方法。。。!)这题更简单的思路适用动态规划,看下面这几行通俗易懂的代码,就知道动态规划有多强了,现在还没有吃过动态规划应用的亏,等什么时候给它坑了的时候,好好写篇博客收了它。
class Solution {
public int maxProfit(int[] prices) {
if(prices.length <= 1)
return 0;
int min = prices[0], max = 0;
for(int i = 1; i < prices.length; i++) {
max = Math.max(max, prices[i] - min);
min = Math.min(min, prices[i]);
}
return max;
}
}
总结
今天写的数组专栏,题目比较简单,所以就没有写在博客里了,明天开始的后四天要打建模比赛了,这期间就不每日打卡刷题了,比赛过后会补回来。除了比赛的那几天,打卡继续。每日打卡第十三天,以下图为证