optimize algorithm as advised by Derianto