How can I solve this classical dynamic programming problem? - dynamic-programming

There are N jewellery shop(s). Each jewellery shop has three kinds of coins - Gold, Platinum, and Diamond having worth value A, B, and C respectively. You decided to go to each of N jewellery shop and take coins from each of the shop. But to do so following conditions must satisfy -
You can take at most 1 coin from an individual shop.
You can take at most X coins of Gold type.
You can take at most Y coins of Platinum type.
You can take at most Z coins of Diamond type.
You want to collect coins from shops in such a way that worth value of coins collected is maximised.
Input Format :
The first line contains an integer N. Where N is the number of jewellery shops.
The second line contains three integers X, Y, Z. Where X, Y, Z denotes the maximum number of coins you can collect of type Gold, Platinum, and diamond respectively.
Then N lines contain three space-separated integers A, B, C. Where A, B, C is the worth value of the Gold, Platinum, and diamond coin respectively.
Output Format :
Print a single integer representing the maximum worth value you can get.
Constraints :
1
<=
N
<=
200
1
<=
X
,
Y
,
Z
<=
N
1
<=
A
,
B
,
C
<
10
9
Example : -
4
2 1 1
5 4 5
4 3 2
10 9 7
8 2 9
Answer:-
27(9+9+5+4)
I tried the obvious greedy approach but it failed :-)

Related

TRUE/FALSE ← VLOOKUP ← Identify the ROW! of the first negative value within a column

Firstly, we have an array of predetermined factors, ie. V-Z;
their attributes are 3, the first two (•xM) multiplied giving the 3rd.
f ... factors
• ... cap, the values in the data set may increase max
m ... fixed multiplier
p ... let's call it power
This is a separate, standalone array .. we'd access with eg. VLOOKUP
f • m pwr
V 1 9 9
W 2 8 16
X 3 7 21
Y 4 6 24
Z 5 5 25
—————————————————————————————————————————————
Then we have 6 columns, in which the actual data to be processed is in, & thereof derive the next-level result, based on the interaction of both samples introduced.
In addition, there are added two columns, for balance & profit.
Here's a short, 6-row data sample:
f • m bal profit
V 2 3 377 1
Y 2 3 156 7
Y 1 1 122 0
X 1 2 -27 2
Z 3 3 223 3
—————————————————————————————————————————————
Ultimately, starting at the end, we are comparing IF -27 inverted → so 27 is within the X's power range ie. 21 (as per the first sample) .. which is then fed into a bigger formula, beyond the scope of this post.
This can be done with VLOOKUP, all fine by now.
—————————————————————————————————————————————
To get to that .. for the working example, we are focusing coincidentally on row5, since that's the one with the first negative value in the 'balance' column, so ..
on factorX = which factor exactly is to us unknown &
balance -27 = which we have to locate amongst potentially dozens to hundreds of rows.
Why!?
Once we know that the factor is X, based on the * & multiplier pertaining to it, then we also know which 'power' (top array) to compare -27, as the identified first negative value in the balance column, to.
Is that clear?
I'd like to know the formula on how to achieve that, & (get to) move on with the broader-scope work.
—————————————————————————————————————————————
The main issue for me is not knowing how to identify the first negative or row -27 pertains to, then having that piece of information how to leverage it to get the X or identify the factor type, especially since its positioned left of the latter & to the best of my knowledge I cannot use negative column index number (so, latter even if possible is out of the question anyway).
To recap;
IF(21>27) = IF(-21<-27)
27 → LOCATE ROW with the first negative number (-27)
21 → IDENTIFY the FACTOR TYPE, same row as (-27)
→ VLOOKUP pwr, based on factor type identified (top array, 4th column right)
→ invert either 21 to a negative number or (-27) to the positive number
= TRUE/FALSE
Guessing your columns I'll say your first chart is in columns A to D, and the second in columns G to K
You could find the letter of that factor with something like this:
=INDEX(G:G,XMATCH(TRUE,INDEX(J:J<0)))
INDEX(J:J<0) converts that column to TRUE and FALSE depending on being negative or not and with XMATCH you find the first TRUE. You could then use that in VLOOKUP:
=VLOOKUP(INDEX(G:G,XMATCH(TRUE,INDEX(J:J<0))),A:D,4,0)
That would return the 21. You can use the first concept too to find the the -27 and with ABS have its "positive value"
=VLOOKUP(INDEX(G:G,XMATCH(TRUE,INDEX(J:J<0))),A:D,4,0) > INDEX(J:J,XMATCH(TRUE,INDEX(J:J<0)))
That should return true or false in the comparison

Hacker rank problem - code optimisation and debugging logical errors required to pass all the test cases for the below python program

This problem is regarding sets, here is an array arr of integers. There are also disjoint sets, A and B, each containing integers. You like all the integers in the set A and dislike all the integers in set B. Your initial happiness is 0. For each integer in the array, if i belongs to A, you add 1 to your happiness. If i belongs to B, you add -1 to your happiness. Otherwise, your happiness does not change. Output your final happiness at the end.
Note: A and B are set, they have no repeated elements. However, the array might contain duplicate elements.
In the below code, I have tried to take input n,m
k = list(map(str,input().split(' ')))
n,m =k
arr=[]
arr = [int(i) for i in input().split()]
arr1 = list( dict.fromkeys(arr) )
A=set(int(i) for i in input().split())
B=set(int(i) for i in input().split())
a=len(set(arr1).intersection(A))
b=len(set(arr1).intersection(B))
print(a-b)
Input Format
The first line contains integers n and m and separated by a space.
The second line contains n integers, the elements of the array.
The third and fourth lines contain m integers, A, and B, respectively.
Input
**1** **2**
3 2 13 4
1 5 3 1 7 8 5 3 7 9 4 9 8 2 1 4
3 1 1 5 3 9
5 7 7 4 2 8
Output
1 0
The above piece of code works for small input test cases but it results as the Wrong answer for the rest.
Follow the link for the actual problem statement
This is the code I used but it was unable to clear most test cases. Need help.

String manipulation with dynamic programming

I have a problem where I have a string of length N, where (1 ≤ N ≤ 10^5). This string will only have lower case letters.
We have to rewrite the string so that it has a series of "streaks", where the same letter is included at least K (1 ≤ K ≤ N) times in a row.
It costs a_ij to change a single specific letter in the string from i to j. There are M different possible letters you can change each letter to.
Example: "abcde" is the input string. N = 5 (length of "abcde"), M = 5 (letters are A, B, C, D, E), and K = 2 (each letter must be repeated at least 2 times) Then we are given a M×M matrix of values a_ij, where a_ij is an integer in the range 0…1000 and a_ii = 0 for all i.
0 1 4 4 4
2 0 4 4 4
6 5 0 3 2
5 5 5 0 4
3 7 0 5 0
Here, it costs 0 to change from A to A, 1 to change from A to B, 4 to change from A to C, and so on. It costs 2 to change from B to A.
The optimal solution in this example is to change the a into b, change the d into e, and then change both e’s into c’s. This will take 1 + 4 + 0 + 0 = 5 moves, and the final combo string will be "bbccc".
It becomes complicated as it might take less time to switch from using button i to an intermediate button k and then from button k to button j rather than from i to j directly (or more generally, there may be a path of changes starting with i and ending with j that gives the best overall cost for switching from button i ultimately to button j).
To solve for this issue, I am treating the matrix as a graph, and then performing Floyd Warshall to find the fastest time to switch letters. This will take O(M^3) which is only 26^3.
My next step is to perform dynamic programming on each additional letter to find the answer. If someone could give me advice on how to do this, I would be thankful!
Here are some untested ideas. I'm not sure if this is efficient enough (or completely worked out) but it looks like 26 * 3 * 10^5. The recurrence could be converted to a table, although with higher Ks, memoisation might be more efficient because of reduced state possibilities.
Assume we've recorded 26 prefix arrays for conversion of the entire list to each of the characters using the best conversion schedule, using a path-finding method. This lets us calculate the cost of a conversion of a range in the string in O(1) time, using a function, cost.
A letter in the result can be one of three things: either it's the kth instance of character c, or it's before the kth, or it's after the kth. This leads to a general recurrence:
f(i, is_kth, c) ->
cost(i - k + 1, i, c) + A
where
A = min(
f(i - k, is_kth, c'),
f(i - k, is_after_kth, c')
) forall c'
A takes constant time since the alphabet is constant, assuming earlier calls to f have been tabled.
f(i, is_before_kth, c) ->
cost(i, i, c) + A
where
A = min(
f(i - 1, is_before_kth, c),
f(i - 1, is_kth, c'),
f(i - 1, is_after_kth, c')
) forall c'
Again A is constant time since the alphabet is constant.
f(i, is_after_kth, c) ->
cost(i, i, c) + A
where
A = min(
f(i - 1, is_after_kth, c),
f(i - 1, is_kth, c)
)
A is constant time in the latter. We would seek the best result of the recurrence applied to each character at the end of the string with either state is_kth or state is_after_kth.

Sum of digits in recursion

Super-sum S of an integer x is defined as x if x is single digit number otherwise Super-sum of x is defined as Super-sum of digit-sum of x. Given two numbers n,k find the Super-sum of the number formed when n is concatenated k times.Note that k is only multiplied with the number when it is at least a 2 digit number
Input:
1987 4
Output:
1
Is there a faster method than this?
s,k=input().split()
summ=0
for ele in s:
summ+=int(ele)
s=summ*int(k)
while s>=10:
s=str(s)
summ=0
for ele in s:
summ+=int(ele)
s=summ
print(s)
n,k=map(int,input().split())
if n<10:
print(n)
else:
if ((n*k)%9==0):
print(9)
else:
res=(n*k)%9
Any number greater than 9 will have digits repeated that's why you need to take mod of 9 for example 13 will have sum of 1+3 =4 and 13 %9=4 .There will be a special case when mod of 9 will be zero and this will be at number 9,18,27,36 etc which are divisible by 9 and their sum will always be 9 hence return 9 .
The formula used in the accepted answer should actually be proved. So, let's do this.
First, let's prove that for any positive integer number N, N modulo 9 is the same sum of its digits modulo 9.
Having proved the statement above, we easily conclude that N % 9 provides the needed digit as per challenge description. The only exception is if N % 9 == 0, then a digit is 9.

Algorithm to find number of possible string variations

For a password related project, I'm looking for an algorithm that calculates the number of possible variations a certain string can have based on a few options. For now the string variation options are upper/lowercase and character to number replacements (like E=3)
For example, lets take the string 'abc#def'
With just upper/lower variations, there are 6 characters that can vary, and the total number of possible variations is 2^6 = 64.
With just character to number replacements, there are 2 characters that qualify (A=4,E=3). That makes the number of variations 2^2 = 4.
I'm struggeling with calculating the number of variations when both methods are enabled.
I've tried (2^6 * 2^4), but obviously this doesn't consider the overlap that occurs when applying both.
For example, the variations 'abc#def' and 'abc#dEf' both result in 'abc#d3f' with number substitution on de character E and should be counted as one.
Somehow I can't figure this out :)
Just count all possibilities for each letter within the password and multiply them together:
letter options count
a a A 4 3
b b B 2
c c C 2
# # 1
d d D 2
e e E 3 3
f f F 2
Finally we have 3 * 2 * 2 * 1 * 2 * 3 * 2 == 144 variants

Resources