private void cancelNegativeCycles() {
        if (!isResidualGraph) {
            throw new IllegalStateException("Should be residual graph to cancel negative cycles");
        }
        boolean cyclePossible = true;
        while (cyclePossible) {
            cyclePossible = false;
            final Map<V, V> parentNodes = new HashMap<>();
            final Map<V, Edge> parentEdges = new HashMap<>();
            final V possibleNodeInCycle = detectNegativeCycles(null, parentNodes, parentEdges);

            if (possibleNodeInCycle == null) {
                continue;
            }

            final Set<V> visited = new HashSet<>();
            V nodeInCycle = possibleNodeInCycle;
            while (!visited.contains(nodeInCycle)) {
                visited.add(nodeInCycle);
                nodeInCycle = parentNodes.get(nodeInCycle);
            }

            cyclePossible = true;
            cancelNegativeCycle(nodeInCycle, parentNodes, parentEdges);
        }
    }
Solve min cost flow with cycle canceling algorithm.
streams/src/main/java/org/apache/kafka/streams/processor/internals/assignment/Graph.java