Maximum Subarray

二、思路及代码

public class Solution {
public int maxSubArray(int[] nums) {
int sum = Integer.MIN_VALUE;
for(int i=0; i<nums.length; i++)
for(int j=i+1; j<nums.length; j++)
sum = Math.min(nums[i]+nums[j], sum);

return sum;
}
}

public class Solution {
public int maxSubArray(int[] nums) {
int sum = nums[0], maxSum = nums[0];
for(int i=1; i<nums.length; i++) {
if(sum < 0) sum = 0; //推断之前的sum能否够利用
sum += nums[i];
maxSum = Math.max(sum, maxSum);
}
return maxSum;
}
}

Maximum Product Subarray

二、代码及思路

public class Solution {
public int maxProduct(int[] nums) {
int localMaxProduct = nums[0], localMinProduct = nums[0], maxProduct = nums[0];

for(int i=1; i<nums.length; i++) {
int copy_localMinProduct = localMinProduct;
localMinProduct = Math.min(Math.min(nums[i]*copy_localMinProduct, nums[i]*localMaxProduct), nums[i]);
localMaxProduct = Math.max(Math.max(nums[i]*copy_localMinProduct, nums[i]*localMaxProduct), nums[i]);
maxProduct = Math.max(localMaxProduct, maxProduct);
}
return maxProduct;
}
}
posted on 2017-08-16 09:23  blfbuaa  阅读(132)  评论(0编辑  收藏  举报