An electrocardiogram signal is a recording of electrical activity at the heart. It is one of the most important signals and is widely used to diagnose abnormalities in the heart. However, it is weak and has a small amplitude, making it vulnerable to noise. One method used to reduce noise is to use the Nonlocal means method. This method has been proven to effectively reduce the amount of noise in an electrocardiogram signal. But the performance of the Nonlocal means method is strongly influenced by three parameters, namely bandwidth λ, patch half-width P, and neighborhood half-width M. In determining the three parameters, it is done manually so the results are not optimum. The analysis was carried out to determine the significance of the three parameters. Based on the results of the analysis it is known that parameter λ has a significant influence on the performance of the Nonlocal means method. If the λ value is too large, dissimilar patches will look similar which result in loss of information. Meanwhile, a small λ will produce a fluctuating signal which contains a lot of noise. Therefore, in this study, we propose an automatic determination of λ parameter to optimize the performance of the Nonlocal means method using the particle swarm optimization method. To measure the performance of the proposed method, we compare it to the state of the art methods such as Wavelet soft thresholding, Empirical Mode Decomposition soft thresholding, Nonlocal means, and modified Empirical Mode Decomposition and Nonlocal means. The results of our experiment showed that our proposed method achieved a better performance in the Mean Squared Error, Percent Distortion, and Signal to Noise Ratio Improvement.