The over-the-air reprogramming has played an important role in Wireless Sensor Networks (WSNs), and has been widely researched. But the problems of low efficiency and high energy consumption have brought new challenges to the research. This paper presents an optimal algorithm, it is targeted to address the problem of relatively low efficiency and high energy consumption in over-the-air reprogramming in WSNs. Simulation results demonstrate that the optimal algorithm can improve the efficiency of over-the-air reprogramming in WSNs, and make the energy consumption in network not only lower but more balanced.