def find_segments(j, e, c, OPT):
    """
    Given an index j, a residuals dictionary, a line cost, and a
    dictionary of optimal costs for each index,
    return a list of the optimal endpoints for least squares segments from 0-j
    """
    if j == -1:
        return []
    else:
        vals = [(e[i][j] + c + OPT[i-1]) for i in range(0, j+1)]
        min_index = vals.index(min(vals))
        return find_segments(min_index-1, e, c, OPT) + [min_index]