optimized algorithm