https://www.hackerrank.com/challenges/sherlock-and-cost/problem
Solution
ref: Blog

We need to find that maximizes the formula above. To maximize the differences, A[i] should be either B[i] or 1, since .
You could brute-force all possibilities for A[i] using BFS or DFS, but with that hits the time limit. Dynamic programming is used to continuously update S[i] and find the maximum S[i].
The cost function returns the largest element of S.
Updating S
A[i] can take one of two values:
- 1
- B[i]
The same goes for A[i - 1].
Generalizing S[i]:
Since A[i] has 2 choices and A[i - 1] also has 2 choices, for a fixed A[i] there are 2 possible values of S[i]. The cases for S[i] are:
- ,
- ,
With this recurrence, S[i] accumulates prior information sequentially to produce the updated S[i].
Code
https://github.com/naem1023/codingTest/blob/master/dp/hackerrank-sherlock-and-cost.py