Cooperative driving emerges as a promising way to improve efficiency and safety for Connected and Automated Vehicles (CAVs). Its key idea is to design a strategy to schedule the movements of neighboring vehicles. The typical cooperative driving strategies can be categorized into two categories. The first category is optimal strategy, which aims to find the globally optimal passing order of vehicles, but the computational cost of this strategy grows significantly with the increasing number of vehicles. The second category is sub-optimal strategy, which uses heuristic rules or other methods to export an acceptable local optimal solution within a limited computation time. However, there usually lacks a rigorous theoretical guarantee of the performances, and further validation is always required for practical applications. To overcome all these limitations, a computationally efficient strategy is proposed to obtain the globally optimal passing order based on dynamic programming (DP). Specifically, the problem of merging at on-ramps is resolved by a DP method, which uses the domain knowledge to reduce the complexity by well defining the state space, state transition, and criterion function. With the DP method, it is proved that the globally optimal passing order can be obtained with the quadratic polynomial computational complexity of O(N^2), where N denotes the number of vehicles. Simulation results demonstrate the performances of the proposed strategy regarding optimality and efficiency.