📖
Coding problems
  • Overview
  • Second time
  • Third time
  • 2 sum
    • 2 sum?
    • 2 Sum All Pair I
    • 2 Sum All Pair II
    • 3 Sum
  • Array
    • Smallest and Largest
    • Largest and second largest
    • Longest Palindromic Substring
  • BFS
    • Array Hopper IV
    • Deep copy graph(possible loops)
    • Kth Smallest With Only 3, 5, 7 As Factors
    • Word Ladder
  • Binary Search
    • Closest in Sorted Array
    • Smallest Element that is larger than target
    • Search in unknown size array
  • Bit Operations
    • Basic Operations
    • Power of two?
    • Different bits
    • Reverse all bits of a number
    • Unique String
  • Deque
    • Deque with 3 stacks
    • Largest Rectangle in histogram
  • DFS Permutations
    • All subsets I
    • All subsets size k
    • Combinations For Telephone Pad I
    • Subsets of all permuations
    • Generate N valid parentheses I
    • Generate N valid parentheses II
    • Generate N valid parentheses III
    • Combinations of Coin
    • All Permutation String
    • All Permutations II
    • Telephone Combinations
  • Dynamic Programming
    • Array Hopper I
    • Array Hopper II
    • Array Hopper III
    • Cut Rope
    • Dictionary Word 1
    • Dictionary Word II
    • Eat Pizza
    • Largest Cross of Ones
    • Largest Square Surrounded By One
    • Largest X of 1s
    • Largest Square of Matches
    • Largest Submatrix Sum
    • Longest Ascending Subsequence I & II
    • Longest Common Sequence between two strings
    • Most with positive slope
    • Palindrome Partition
    • Edit Distance
    • Square of ones
    • Wild card matching
    • Wood Cutting
    • 188. Best Time to Buy and Sell Stock IV
  • Graph Search
    • Kth closest to <0, 0, 0>
    • Largest Product of Length
  • HashTable
    • Top K frequent words
    • Bipartite
  • Heap
  • LinkedList
    • Reverse
    • Merge Sort Linked List
    • Re-Order LinkedList
  • Slow fast pointers
    • Remove duplicate elements in array
  • Problem Solving
    • Water Level I
    • Largest rectangle in histogram
    • Range Addition II
  • Recursion
    • ReverseTree
    • NQueen
    • NQueen optimized
    • Spiral Order Print I
    • Spiral Order Print II
    • String Abbreviation Matching
  • Sliding Window
    • Longest subarray contains only 1s
    • Longest Substring Without Repeating Characters
    • Maximum Number within Window
  • Sorts
    • QuickSort
  • String
    • All Anagrams
    • is substring of string
    • Reverse String
    • Reverse Words on sentence
    • Remove Chars from String in place
    • Right shift N characters
    • Remove Leading/duplicate/trailing spaces
    • Shuffle String
    • String Abbreviation Matching
  • Tree Traversal
    • Check balanced tree
    • Check if complete tree
    • Delete in binary tree
    • LCA of two tree nodes
    • Get Keys In Binary Search Tree In Given Range
    • Height of Tree
    • Symmetric Tree?
    • Tweaked Binary tree
    • Set left node count
    • Greatest difference Left and Right subtree count Node
    • Largest Number Smaller in BST
    • Closest Number in Binary Search Tree II
    • Max Path Sum From Leaf To Root
    • Maximum Path Sum Binary Tree I
    • Maximum Path Sum Binary Tree II
    • Maximum Path Sum Binary Tree III
    • Flatten Binary Tree to Linked List
    • Iterative Post-Order Traversal
  • Unsorted Array
    • Find missing number
Powered by GitBook
On this page

Was this helpful?

There is a wooden stick with length L >= 1, we need to cut it into pieces, where the cutting positions are defined in an int array A. The positions are guaranteed to be in ascending order in the range of [1, L - 1]. The cost of each cut is the length of the stick segment being cut. Determine the minimum total cost to cut the stick into the defined pieces.

Examples

  • L = 10, A = {2, 4, 7}, the minimum total cost is 10 + 4 + 6 = 20 (cut at 4 first then cut at 2 and cut at 7)

Solution: 2D DP

Key insights:

  1. left stick does not affect right stick

  2. Treat the cuts as segments, account for indexes only

  3. Treat as merging problem

Base Case:

Adjacent index can not be cut further, thus = zero

Inductive Rule:

  1. Iterate through all possible merge locations of current segment length

  2. Cost of current merge = Length of substick created + left stick creation cost + right stick creation cost

ex: 4 index stick

--- -

-- --

- ---

Time Complexity: O(N * N / 2) tiles to fill * O(N) check merges = O(N^3)

Space Complexity: M[ ] = O(N * N) = O(N^2)

Last updated 4 years ago

Was this helpful?

public class Solution {
  public int minCost(int[] cuts, int length) {    
    //sanity check
    if (cuts.length == 0 || length <= 0) return 0;

    //add 0 and Length cut to cuts
    List<Integer> arr = new ArrayList<>();
    arr.add(0);
    for (int x: cuts){
      arr.add(x);
    }
    arr.add(length);

    int[][] M = new int[arr.size()][arr.size()];

    //Base Cases: adjacent indexes cost 0, cant be cut
    for (int i = 0; i < arr.size() - 1; i++){
      M[i][i + 1] = 0;
    }

    //{0,2,4,7,10}
    //size = 5
    //greatest substick = 4

    int offset = 2; //substick lengths we are calculating
    while(offset < arr.size()){ //stop if more substicks than elements in cuts
      for(int left = 0; left + offset < arr.size(); left++){ //left index of substick
        int right = left + offset;
        Integer min = Integer.MAX_VALUE; //min cost of M[left][right]
        int mergeCost = arr.get(right) - arr.get(left);

        for (int k = left + 1; k < right; k++){
          int leftCost = M[left][k];
          int rightCost = M[k][right];
          int curCost = leftCost + rightCost;
          if (curCost < min){
            min = curCost;
          }
        }

        M[left][right] = mergeCost + min;
      }

      offset += 1;
    }
    
    return M[0][arr.size() - 1];
  }
}
  1. Dynamic Programming

Wood Cutting

PreviousWild card matchingNext188. Best Time to Buy and Sell Stock IV