public class Solution {
public int maxProfit(int[] prices) {
int profit = 0;
if(null == prices || prices.length < 1)
return profit;
int [] diff = new int[prices.length];
diff[0] = 0;
for(int i=1; i<prices.length; i++)
diff[i] = prices[i] - prices[i-1];
int temp = 0;
for(int i=0; i<diff.length; i++){
if(temp <0)
temp = diff[i];
else
temp += diff[i];
if(profit < temp)
profit = temp;
}
return profit;
}
}
本题即为求解一个数组中的最大差值。解题思路是先求出数组的相邻增量数组,转化为求增量数组的连续子数组的最大和问题。
一开始使用两层循环来求解,在leetcode提交时导致Timeout的问题。如下所示(低效算法):
public class Solution {
public int maxProfit(int[] prices) {
int profit = 0;
if(null == prices || prices.length < 1)
return profit;
for(int i=0; i<prices.length; i++)
for(int j=i+1; j<prices.length; j++)
if(prices[j]-prices[i] > profit)
profit = prices[j] - prices[i];
return profit;
}
}
Submission Result: Time Limit Exceeded
Last executed input: | [10000,9999,9998,9997,9996,9995,9994,9993,9992,9991,9990,9989,9988,9987,9986,9985,9984,9983,9982,9981...] |