📌  相关文章
📜  根据给定条件的数组元素的最小总和

📅  最后修改于: 2021-04-27 18:06:46             🧑  作者: Mango

给定大小为N的数组A [] ,其中的条目为整数,则某些条目为-1。任务是用满足以下条件的数字替换-1。

  1. 要替换的数字的二进制表示形式的奇数位置应仅包含0,数字必须为偶数。
  2. 替换为-1的数组项A [i]的方式为: A [i]> = A [i-1]以及给定数组A [0]!=-1

    完成上述操作后,找到数组条目的最小和。

例子:

方法:

  • 使用线性搜索遍历数组以标识所有-1。
  • 无论哪里有-1,都会从索引比当前索引小1的数字开始生成另一个while循环。
  • 检查所有进行中的项的二进制表示形式的奇数位置,如果它仅包含预期的零,则跳出循环,否则将迭代器加1,直到达到所需的数量。
  • 当满足所需的数字时,给定索引处的相应元素将替换为满足所有条件的新数字。
  • 计算所有-1替换后的数组项总和。

下面是上述方法的实现:

# Find the minimum sum of array 
# entries following given criteria.
def Bit_Even_Arrays(arr):
  
    # Iterating through the 
    # array to find -1's
    for k, v in enumerate(arr):
        z = 0
        if v == -1:
  
            # Starting from the entry
            # with index 1 less than -1
            # as A[i]>= A[i-1]
            y = k - 1
            z = arr[y]
  
            # Initiating the infinite series
            # that satisfies given criteria 
            # and breaking out of the loop
            # once it satisfies
            while True:
                S = bin(z)[2:][1::2]
                if (z % 2 == 0) \
                          &(len(set(S))== 1)\
                            & ('0' in set(S)):
                    break
                else:
   
                    # incrementing the entry
                    # until the required 
                    # entry is met
                    z += 1 
            arr[k]= z
    return (sum(arr)) 
  
# Driver code
if __name__ == '__main__':
      arr = [1, 5, -1, 25, -1, 7, 35, -1]
      print (Bit_Even_Arrays(arr))
输出:
153