二进制数组函数解决方案

huangapple go评论75阅读模式
英文:

Binary Array Function Solution

问题

以下是翻译好的部分:

一个接受二进制数组作为输入的函数找出在只能对子数组进行一次操作的情况下数组中存在的最大零的数量该操作可以将子数组的元素翻转即将0变为1将1变为0

有人能否用Python编写程序考虑到所有边界情况

我尝试过使用ChatGPT和其他人工智能但无法解决一些隐藏的测试案例我也想不出可能失败的测试案例

一些示例测试案例如下
输入: [ 0, 1, 0, 0, 1, 1, 0 ]
输出: 6

输入: [ 0, 0, 0, 0, 0 ]
输出: 5

我需要帮助创建一个接受二进制数组输入并返回输出的完整函数
英文:

A function that takes a binary array as input and finds out the maximum no. of zeroes present in the array after applying only one operation in which we can flip the elements of a subarray i.e. changing 0 to 1 and vice versa.

Can someone write the program in python considering all the edge cases.

I tried using chatgpt and other AI but could solve some of the hidden test cases and I can't think of a test cases which might be failing.

Some example test cases are:
Input : [ 0, 1, 0, 0, 1, 1, 0 ]
Output : 6

Input : [ 0, 0, 0, 0, 0 ]
Output : 5

I need help in creating the complete function which takes the binary array input and return the output.

答案1

得分: 1

the trick is to find the longest subarray containing ones and flipping its values then counting the zeros.

def foo(list1):
    # 先寻找包含1的最长子数组
    start_index = 0  # 最长子数组的起始索引
    length = 0  # 包含的元素数量

    for i in range(len(list1)):

        if list1[i] == 1:  # 找到一个1,检查后面有多少个1

            j = i
            temp_length = 0

            while j < len(list1) and list1[j] == 1:
                j += 1
                temp_length += 1
            if temp_length > length:
                start_index = i
                length = temp_length

    # 翻转该子数组中的值为0
    list1[start_index:start_index + length] = [0] * length

    # 返回0的计数
    return list1.count(0)
英文:

the trick is to find the longest subarray containing ones and flipping its values then counting the zeros.

def foo(list1):
    # first search for the longest subarray containing ones
    start_index=0 # start index of the longest subarray
    length=0 # number of elements it contains
    
    for i in range(len(list1)):
        
        if list1[i]==1: # we have found a one, check how many ones come after it
            
            j=i
            temp_length=0
    
            while  j&lt;len(list1) and list1[j]==1:
                j+=1
                temp_length+=1
            if temp_length&gt;length:
                start_index=i
                length=temp_length

    # flip the values in that subarray to zeros
    list1[start_index:start_index+length]=[0]*length

    # return the count of zeros
    return list1.count(0)

huangapple
  • 本文由 发表于 2023年7月17日 15:28:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76702305.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定