Sherlock and Cost Discussions | Algorithms | HackerRank
  • + 21 comments

    "Wording of problem statement" is perhaps the only thing difficult about this problem. Coders are needlessly getting confused by that. Few points to avoid confusion :

    • Array B containing elements B1, B2,..., Bn is provided as input.

    • Elements A1, A2,.., An for array A has to be decided by the coder/code. An element Ai can be any integer such that 1 <= Ai <= Bi.

    • Select elements for array A such that it maximizes S (sum of difference between consecutive elements of A).

    • Output required : the maximized value S.


    Example : Suppose B = [2, 4, 3]. Then 1<=A1<=2, 1<=A2<=4 and 1<=A3<=3. Hence, there are 24 possible options for A, some of them are :

    [1, 1, 3]   [1, 2, 3]   [1, 3, 3]   [1, 4, 1]
    [2, 1, 2]   [2, 2, 2]   [2, 3, 3]   [2, 4, 1]
    

    Out of all the possible options, A = [1, 4, 1] maximizes S.

    Thus, the answer is : |4-1| + |1-4| = 3 + 3 = 6.


    PS : Only Sherlock knows why the problem is named "Sherlock and Cost" ! ;-)