Daily Archives: April 20, 2016

Integer Break

https://leetcode.com/problems/integer-break/

Given a positive integer n, break it into the sum of at least two positive integers and maximize the product of those integers. Return the maximum product you can get.

For example, given n = 2, return 1 (2 = 1 + 1); given n = 10, return 36 (10 = 3 + 3 + 4).

Solution. This is a classical dp problem.

For n, split n to left and right part. So, left part has i, right part has n – i. Then we calculate leftMax and rightMax:
leftMax = max(i, dp[i])
rightMax = max(n – i, dp[n – i])

so, dp[n] = max(leftMax * rightMax)

check my code on github: java, python

Flatten Nested List Iterator

Given a nested list of integers, implement an iterator to flatten it.

Each element is either an integer, or a list — whose elements may also be integers or other lists.

Example 1:
Given the list [[1,1],2,[1,1]],

By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1].

Example 2:
Given the list [1,[4,[6]]],

By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6].

Solution. This problem is the same as deepIterator. Each time, we store the iterator of the list in stack. But in my previous deepIterator, I didn’t handle when a list is empty.

For this problem, I use currInteger to tell if iterator has next.

The main part is the refresh() function. It iterates until it finds an element is Integer. When current iterator doesn’t has next or list is totally empty, it pops the stop. When current element is a list, it pushes to stack.

private void refresh() {
    currInteger = null;
    while (!s.isEmpty()) {
        if (!s.peek().hasNext()) {  // iterator is empty. Another situation could be that iterator for the list is empty at all
            s.pop();
            continue;
        }
        NestedInteger curr = s.peek().next();
        if (curr.isInteger()) {
            currInteger = curr.getInteger();
            return;
        }
        // comes to here, it means it is a list
        s.push(curr.getList().iterator());
    }
}

Check my code on github: link