最小化对给定 Array 的相邻元素执行的算术运算以减少它
给定一个数组arr[] ,任务是按顺序对arr[]执行算术运算(+、-、*、/) 。对相邻元素执行这些操作,直到数组大小减小到1 。最后,返回减少的值和所需的操作数。请参阅示例以获得更清晰的信息。
例子:
Input: arr = {12, 10, 2, 9, 1, 2}
Output: Reduced Value: 10
Operations Performed:
+ : 2
– : 1
* : 1
/ : 1
Explanation:
Step 1: perform addition of consecutive element [22, 12, 11, 10, 3]
Step 2: perform subtraction of consecutive element [10, 1, 1, 7]
Step 3: perform multiplication of consecutive element[10, 1, 7]
Step 4: perform division of consecutive element [10, 0]
Step 5: Again perform addition of consecutive element[10]
Input: arr = {5, -2, -1, 2, 4, 5}
Output: Reduced Value: -3
Operations Performed:
+ : 2
– : 2
* : 1
/ : 1
方法:由于在这个问题中,我们必须根据顺序执行运算,例如先加法然后减法,然后乘法然后除法,因此我们可以使用 Switch case 来解决这个问题。
初始化一个字典,其中运算符(+、-、*、/)作为键,0 作为值。使用函数add、sub、mul和div,将对数组执行操作。它具有 as函数Operation,它根据c%4的值将数组映射到函数并返回缩减后的数组。其中c跟踪执行的操作数。字典跟踪执行的每个操作,直到数组大小减少到1 。
请按照以下步骤解决给定的问题。
第 1 步:将c赋值为1并声明字典d 。
- 步骤 2:如果c%4==1则使用 Operation 函数对连续元素执行加法运算。
- 第 3 步:如果c%4==2则使用运算函数对连续元素执行减法运算。
- 第 4 步:如果c%4==3则使用 Operation 函数对连续元素执行乘法运算。
- 步骤 5:如果c%4==0则使用 Operation 函数对连续元素执行除法运算。
- 第 6 步:将重复第2步,直到数组的大小等于1 。
- 步骤 7: d用于跟踪执行的每个操作。
下面是上述方法的实现:
Python3
# Function for adding consecutive element
def add(a):
return [a[i]+a[i + 1] for i in range(len(a)-1)]
# Function for subtracting consecutive element
def sub(a):
return [a[i] - a[i + 1] for i in range(len(a)- 1)]
# Function for multiplication of consecutive element
def mul(a):
return [a[i] * a[i + 1] for i in range(len(a) - 1)]
# Function for division of consecutive element
def div(a):
return [0 if a[i] == 0 or a[i + 1] == 0 \
else a[i]//a[i + 1] \
for i in range(len(a) - 1)]
# Operation function which maps array
# to corresponding function
# based on value of i.
def Operation(i, A):
switcher = {
1: add,
2: sub,
3: mul,
0: div
}
func = switcher.get(i, lambda: 'Invalid')
return func(A)
# Driver Code
c = 1
# dictionary value which keep track
# of no of operation of each operator.
d = {'+':0, '-':0, '*':0, '/':0 }
arr =[5, -2, -1, 2, 1, 4, 5]
# loop till size of array become equal to 1.
while len(arr)!= 1:
x = c % 4
# After each operation value
# in dictionary value is incremented
# also reduced array
# is assigned to original array.
if x == 1:
d['+'] += 1
arr = Operation(x, arr)
elif x == 2:
d['-'] += 1
arr = Operation(x, arr)
elif x == 3:
d['*'] += 1
arr = Operation(x, arr)
elif x == 0:
d['/'] += 1
arr = Operation(x, arr)
c += 1
# Printing reduced value
print("Reduced value:", *arr)
# Printing value of each operation
# performed to reduce size of array to 1.
print("Operations Performed:")
for i in d.keys():
print(str(i) + " : " +str(d[i]))
Reduced value: -3
Operations Performed:
+ : 2
- : 2
* : 1
/ : 1
时间复杂度: O(N)
辅助空间: O(N)