动态规划系列(6) leetcode java篇

这篇博客介绍了如何使用动态规划解决两个数组相关的问题:找到一个整数数组中乘积最大的非空连续子数组以及乘积为正数的最长子数组。第一个问题通过维护最大值和最小值来更新当前最大乘积,第二个问题通过跟踪正负数的计数来确定最长正乘积子数组的长度。这两个算法都有效地解决了数组处理中的优化问题。
摘要由CSDN通过智能技术生成

第一题:

乘积最大子数组

给你一个整数数组 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;
    }
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Frank.Ren

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值