第一题:
给你一个整数数组 nums ,请你找出数组中乘积最大的非空连续子数组(该子数组中至少包含一个数字),并返回该子数组所对应的乘积。
测试用例的答案是一个 32-位 整数。
子数组 是数组的连续子序列。
class Solution {
public int maxProduct(int[] nums) {
int len = nums.length;
if(nums==null||len==0){
return 0;
}else if(len==1){
return nums[0];
}
int min = nums[0];
int max = nums[0];
int ret = nums[0];
for(int i = 1;i<len;i++){
int mx = max;
int mn = min;
max = Math.max(nums[i]*mx,Math.max(nums[i]*mn,nums[i]));
min = Math.min(nums[i]*mn,Math.min(nums[i]*mx,nums[i]));
ret = Math.max(max,ret);
}
return ret;
}
}
第二题:
给你一个整数数组 nums ,请你求出乘积为正数的最长子数组的长度。
一个数组的子数组是由原数组中零个或者更多个连续数字组成的数组。
请你返回乘积为正数的最长子数组长度。
public class Solution {
public int getMaxLen(int[] nums) {
int length = nums.length;
int positive = nums[0] > 0 ? 1 : 0;
int negative = nums[0] < 0 ? 1 : 0;
int max = positive;
for (int i = 1; i < length; i++) {
if (nums[i] > 0) {
positive++;
negative = negative > 0 ? negative + 1 : 0;
} else if (nums[i] < 0) {
int newPositive = negative > 0 ? negative + 1 : 0;
int newNegative = positive + 1;
positive = newPositive;
negative = newNegative;
} else {
positive = 0;
negative = 0;
}
max = Math.max(max, positive);
}
return max;
}
}
第三题:
给你一个正整数数组 values,其中 values[i] 表示第 i 个观光景点的评分,并且两个景点 i 和 j 之间的 距离 为 j - i。
一对景点(i < j)组成的观光组合的得分为 values[i] + values[j] + i - j ,也就是景点的评分之和 减去 它们两者之间的距离。
返回一对观光景点能取得的最高分。
class Solution {
public int maxScoreSightseeingPair(int[] values) {
int len = values.length;
int pre = values[0];
int max = values[0]+values[1]-1;
for(int i =1;i<len;i++){
max = Math.max(max,pre+values[i]-i);
pre = Math.max(pre,values[i]+i);
}
return max;
}
}