Melanoma, a prevalent and formidable skin cancer, necessitates early detection for improved survival rates. The rising incidence of melanoma poses significant challenges to healthcare systems worldwide. While deep neural networks offer the potential for precise melanoma classification, the optimization of hyperparameters remains a major obstacle. This paper introduces a groundbreaking approach that harnesses the Manta Rays Foraging Optimizer (MRFO) to empower melanoma classification. MRFO efficiently fine-tunes hyperparameters for a Convolutional Neural Network (CNN) using the ISIC 2019 dataset, which comprises 776 images (438 melanoma, 338 nonmelanoma). The proposed cost-effective DenseNet121 model surpasses other optimization methods in various metrics during training, testing, and validation. It achieves an impressive accuracy of 99.26%, an AUC of 99.56%, an F1 score of 0.9091, a precision of 94.06%, and a recall of 87.96%. Comparative analysis with EfficientB1, EfficientB7, EfficientNetV2B0, NesNetLarge, ResNet50, VGG16, and VGG19 models demonstrates its superiority. These findings underscore the potential of the novel MRFO-based approach in achieving superior accuracy for melanoma classification. The proposed method has the potential to be a valuable tool for early detection and improved patient outcomes.