之前没想出来,今天忘了是看算法导论还是另一本算法书讲到了最大子序列,正好就拿这道题做例子,一种方法是二分递归两边的最大子序列,然后再合并,计算穿过中界线的最大序列进行递归求最大值。还有一种更好的方法是类似于GAS 那道题,求出变化量数组,然后相加,如果总和为负,则序列从新开始。这样只需O(n)的时间复杂度。
public int maxProfit(int[] prices) {
int num = prices.length;
if(num==0||num==1)return 0;
int[] pr = new int[num-1];
for(int i=0;i<num-1;i++){
pr[i]=prices[i+1]-prices[i];
}
int max=0;
int thi=0;
for(int i=0;i<num-1;i++){
thi=thi+pr[i];
if(thi>max) max=thi;
if(thi<0) thi=0;
}
return max;
}Update 2015/08/21: 思路同上,只是优化了一下
public class Solution {
/**
* @param prices: Given an integer array
* @return: Maximum profit
*/
public int maxProfit(int[] prices) {
// write your code here
int len = prices.length - 1;
for (int i = 0; i< len; i++){
prices[i] = prices[i + 1] - prices[i];
}
int global = 0;
int local = 0;
for (int i = 0; i< len; i++){
local = local + prices[i];
if (local < 0){
local = 0;
}
global = Math.max(global, local);
}
global = Math.max(global, local);
return global;
}
}
本文介绍了一种优化后的算法,用于解决股票投资中的最大利润问题。通过引入变化量数组和动态规划思想,该算法能在O(n)时间内高效求解。详细解释了算法原理、步骤和代码实现,并提供了优化思路。
679

被折叠的 条评论
为什么被折叠?



