0% found this document useful (0 votes)
5 views2 pages

Untitled Document

Uploaded by

adeefhaayaz01
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views2 pages

Untitled Document

Uploaded by

adeefhaayaz01
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

PF ASSIGNMENT

Name: Adeefah Ayaz


Department: BSCS
Section: I

Question:
Find ways to calculate a target from elements of the specified array. Given an
integer array, return the total number of ways to calculate the specified target from array
elements using only the addition and subtraction operator. The use of any other
operator is
forbidden.
Consider the array { 5, 3, -6, 2 }.
The total number of ways to reach a target of 6 using only + and – operators is 4 as:
(-)-6 = 6
(+) 5 (+) 3 (-) 2 = 6
(+) 5 (-) 3 (-) -6 (-) 2 = 6
(-) 5 (+) 3 (-) -6 (+) 2 = 6
Similarly, there are 4 ways to calculate the target of 4:
(-)-6 (-) 2 = 4
(-) 5 (+) 3 (-)-6 = 4
(+) 5 (-) 3 (+) 2 = 4
(+) 5 (+) 3 (+)-6 (+) 2 =4

Answer:
Problem Statement:

Given an integer array, return the total number of ways to calculate the specified target
from array elements using only the addition and subtraction operator.

Example:

Input: arr = [5, 3, -6, 2], target = 6


Output: 4
Explanation:

There are 4 ways to calculate the target of 6:


(-)-6 = 6
(+)-5 (+) 3 (-) 2 = 6
(+)-5 (-) 3 (-)-6 (-) 2 = 6
(-)-5 (+) 3 (-)-6 (+) 2 = 6

Task:

Write a Python function find_target_ways that takes an integer array arr and a target
integer target as input and returns the total number of ways to calculate the target from
array elements using only the addition and subtraction operator.

Solution:

def find_target_ways(arr, target):


dp = {0: 1}
for num in arr:
temp = {}
for sum_val, count in dp.items():
temp[sum_val + num] = temp.get(sum_val + num, 0) + count
temp[sum_val - num] = temp.get(sum_val - num, 0) + count
dp = temp
return dp.get(target, 0)

Test Case:

arr = [5, 3, -6, 2]


target = 6
print(find_target_ways(arr, target))

Output:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy