Dividing a water distribution network (WDN) in the optimal district metered areas (DMAs) formation is one task that usually troubles water utility managers. The present paper utilizes optimization methods to achieve desired segmentation conditions in terms of (a) operating pressure reduction, thus reducing the system's real water losses and (b) residual chlorine concentration reduction thus preventing disinfection byproducts' growth. Exploiting the numerous possibilities offered by the inter-connection of Matlab and EPANET software tools, an algorithm is developed in C++ language. The algorithm reads all significant data of a WDN as an output of EPANET. The first algorithm calculates the optimal allocation of a given number of closed isolation valves in terms of water losses' reduction, considering restrictions for network's proper operation. The second algorithm calculates the optimal formation of DMAs in terms of water quality improvement. Both algorithms can be applied in any WDN. The outcome is the optimal set of closed pipes that leads to the optimal formation of DMAs in a given network. The closing of pipes (by installing isolation valves) determines the optimal formation of DMAs. The basic concept of both algorithms and their application in a case study network's hydraulic model are presented.