With the increasing popularity and development of electric vehicles, the demand for electric vehicle charging is also constantly increasing. To meet the diverse charging needs of electric vehicle users and improve the efficiency of charging infrastructure, this study proposes an optimization strategy for electric vehicle charging and discharging. This method considers both the user’s travel mode and the operational efficiency of the charging pile. Firstly, a probability model based on travel spatiotemporal variables and Monte Carlo algorithm were used to simulate the travel trajectory of electric vehicles, providing a data foundation for optimizing the charging and discharging schemes of electric vehicles. Then, with the dual objective of minimizing the operating costs of charging piles and user charging costs, a linear programming model was constructed to optimize the charging and discharging strategies of electric vehicles. Finally, the model was validated using an apartment building as an example. The results indicate that, under the normal travel habits of users, with the goal of minimizing company expenses, the annual cost of the company reaches its minimum at a certain number of charging piles. When the cost of electric vehicle users dominates the objective function, they will pay more attention to battery degradation, significantly reducing their willingness to participate in discharge.