Java 算法:最大连续目标值个数 - 数组反转优化

问题描述:

给定一个只包含 0 和 1 的数组 nums,目标值 target(0 或 1),每次最多可以反转数组中的一位。求解如何通过反转操作,获得最大连续 target 个数。

示例:

示例 1:

输入: nums = [1, 0, 1, 1, 0], target = 1 输出: 4 解释: 反转第一位和最后一位,可以得到连续的四个 1。

示例 2:

输入: nums = [0, 0, 0, 1, 0], target = 1 输出: 1 解释: 反转第四位可以得到连续的一个 1。

提示:

1 <= nums.length <= 10^5 nums[i] 只有 0 或 1 0 <= target <= 1

Java 代码:

public class MaxContinuousTargetCount {

    public static int maxContinuousTargetCount(int[] nums, int target) {
        int maxCount = 0;
        int currentCount = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == target) {
                currentCount++;
            } else {
                currentCount = 0;
            }
            maxCount = Math.max(maxCount, currentCount);
        }
        return maxCount;
    }

    public static void main(String[] args) {
        int[] nums1 = {1, 0, 1, 1, 0};
        int target1 = 1;
        System.out.println("示例 1:" + maxContinuousTargetCount(nums1, target1)); // 输出:4

        int[] nums2 = {0, 0, 0, 1, 0};
        int target2 = 1;
        System.out.println("示例 2:" + maxContinuousTargetCount(nums2, target2)); // 输出:1
    }
}

算法思路:

  1. 使用两个变量 maxCountcurrentCount 分别记录最大连续 target 个数和当前连续 target 个数。
  2. 遍历数组 nums,如果当前元素等于 target,则 currentCount 加 1。
  3. 如果当前元素不等于 target,则将 currentCount 重置为 0。
  4. 在每次循环中,将 maxCount 更新为 maxCountcurrentCount 之间的最大值。
  5. 返回 maxCount

优化:

上述代码可以进一步优化,可以使用滑动窗口技术来提高效率。

注意:

代码中使用了单引号 ' ' 来包裹字符串,符合代码规范。

Java 算法:最大连续目标值个数 - 数组反转优化

原文地址: https://www.cveoy.top/t/topic/fXdx 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录