1.leetcode#53. Maximum Subarray

1.1题目描述

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.

1.3代码

public int maxSubArray(int[] nums) {
if(nums==null||nums.length==0) return 0;
#全局最大
int max=Integer.MIN_VALUE;
#局部最大
int tempmax=0;
for(int i=0;i<nums.length;i++){
tempmax=tempmax+nums[i];
//状态转移
tempmax=tempmax>nums[i]?tempmax:nums[i];
//和全局比较
max=max>tempmax?max:tempmax;
}
return max;
}

2.leetcode#152. Maximum Product Subarray

2.1题目描述

Find the contiguous subarray within an array (containing at least one number) which has the largest product.

For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.

2.3代码

public int maxProduct(int[] nums) {
if(nums==null){
return 0;
}
int max=nums[0];
int min=nums[0];
int globalmax=nums[0];
//int globalmin=nums[0];
for(int i=1;i<nums.length;i++){
int tempmax=max*nums[i];
int tempmin=min*nums[i];
//如果最小值和最大值互换了
if(tempmin>tempmax){
int temp=tempmax;
tempmax=tempmin;
tempmin=temp;
}
//局部最大，局部最小
max=tempmax>nums[i]?tempmax:nums[i];
min=tempmin<nums[i]?tempmin:nums[i];
//全局最大
globalmax=globalmax>max?globalmax:max;
//全局最小
//globalmin=globalmin<min?globalmin:min;
}
return globalmax;
}

3.子矩阵最大累加和

3.1代码

public static int MaximumSum(int[][] Matrix){
int max=Integer.MIN_VALUE;
for(int i=0;i<Matrix.length;i++){
int[] sum=new int[Matrix[0].length];
for(int j=i;j<Matrix.length;j++){
//进行累加
for(int col=0;col<Matrix[0].length;col++){
sum[col]+=Matrix[j][col];
}
int tempmax=maxSubArray(sum);
max=max>tempmax?max:tempmax;
}
}
return max;
}