I gather you want a method to figure out the best fitting key.
Lets first note (no pun) that a key name is just the first note of the respective scale so the name of the key doesn't have to be sharp or flat to represent a collection of sharp or flats notes.
For example, key of G, representing a Gmajor scale (major is the default) contains one sharp, being F#.
The key names, and the accidentals they contain, follow the 5ths pattern of F,C,G,D,A,E,B.
C has 0 sharps/flats; G has one sharp (F#), and the next one up is D, which contains both the F# carried over from G as well as a C#.
As you can see the accidentals being added also follow the same FCG fifths pattern except they're sharped - F#,C#,G#,D#,A#,E#,B#,
This means that if you have F# notes in your piece then you're at least a key of G. If you have F# and C# notes then the key of D also works, better, as it covers an additional accidental.
Conversely if the sharps notes in your piece are not F#, not C#, etc. then it's perhaps not best represented by a sharp key.
If that's so then consider your sharp notes as flats, the enharmonic equivalents, such as G# which can also be A-flat, and repeat the exercise for the flat keys.
Flat keys follow a similar pattern as sharps but they're going right to left on the list of 5ths, being, for three octaves:
F(flat),C(flat),G(flat),D(flat),A(flat),E(flat),B(flat),F,C,G,D,A,E,B,F#,C#,G#,D#,A#,E#,B#.
That is, key of C has an F note (one to the left) and the key of F adds a B(flat).
The key of E(flat) adds an A(flat) - three flats total, A(flat),E(flat),B(flat).
So if you have B(flat) notes then you're good for the key of F.
If you then also have E(flat) notes then you're good for the key of B(flat), and so forth.
But of course you can have notes that are not in a respective key ... they are "chromatic", not "diatonic", so they may have to remain as notated as flats or sharps notes in the piece.
You're looking for the best key, not the 'right' one.
There's hundreds of videos introducing key signatures. I looked at a half-dozen for this answer and these two are concise.