intscoreHand(vector<string>cards){unordered_map<string,int>scoreCount;// holds the score of each cardfor(inti=2;i<=10;i++){scoreCount[to_string(i)]=i;}scoreCount["A"]=1;// store the score of A as 1 (minimum)scoreCount["J"]=10;scoreCount["K"]=10;scoreCount["Q"]=10;unordered_map<string,int>cardCount;// holds the number of times cards are apperaingintscore=0;// minimum score (i.e. score with A as 1)for(strings:cards){score+=scoreCount[s];cardCount[s]++;}// if score is 21 return 21if(score==21)returnscore;// if score < 21 try to maximize it// but keep it less than or equal to 21if(score<21){for(inti=0;i<cardCount["A"];i++){if(score>11){returnscore;}// add score of A to score// score = score - 1 + 11score+=10;}}// no need to write the case when score > 21// because we are always starting from minimum score possiblereturnscore;}
Code can be optimized by caculating scoreCount seperately and then passing
it as an argument in the function.
C++
Code can be optimized by caculating
scoreCount
seperately and then passingit as an argument in the function.
Test cases --
Output --