Minimum cost to complete given tasks if cost of 1 , 7 and 30 days are given | Function to find the minimum cost to hire the workers for the given days in the array days [ ] ; Initialize the array dp ; Minimum Cost for Nth day ; Pointer of the array arr [ ] ; Traverse from right to left ; If worker is hired for 1 day ; If worker is hired for 7 days ; If worker is hired for 30 days ; Update the value of dp [ i ] as minimum of 3 options ; If the day is not at the array arr [ ] ; Return the answer ; Driver Code
function MinCost ( days , cost , N ) { let size = days [ N - 1 ] + 1 ; let dp = new Array ( size ) ; dp [ size - 1 ] = Math . min ( cost [ 0 ] , Math . min ( cost [ 1 ] , cost [ 2 ] ) ) ; let ptr = N - 2 ; for ( let i = size - 2 ; i > 0 ; i -- ) { if ( ptr >= 0 && days [ ptr ] == i ) { let val1 = dp [ i + 1 ] + cost [ 0 ] ; let val2 = cost [ 1 ] + ( ( i + 7 >= size ) ? 0 : dp [ i + 7 ] ) ; let val3 = cost [ 2 ] + ( ( i + 30 >= size ) ? 0 : dp [ i + 30 ] ) ; dp [ i ] = Math . min ( val1 , Math . min ( val2 , val3 ) ) ; ptr -- ; } else { dp [ i ] = dp [ i + 1 ] ; } } return dp [ 1 ] ; } let arr = [ 2 , 4 , 6 , 7 , 8 , 10 , 17 ] ; let cost = [ 3 , 8 , 20 ] ; let N = arr . length ; document . write ( MinCost ( arr , cost , N ) ) ;