From 67b628c4222df21f9fb69b60e35a942378f69657 Mon Sep 17 00:00:00 2001 From: Aniket Kumar Date: Thu, 30 Sep 2021 21:53:27 +0530 Subject: [PATCH] #67 added leetcode-1748 solution.cpp --- .../1748_Sum of Unique Elements/Solution.cpp | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Algorithms/Easy/1748_Sum of Unique Elements/Solution.cpp diff --git a/Algorithms/Easy/1748_Sum of Unique Elements/Solution.cpp b/Algorithms/Easy/1748_Sum of Unique Elements/Solution.cpp new file mode 100644 index 0000000..6b0fa9f --- /dev/null +++ b/Algorithms/Easy/1748_Sum of Unique Elements/Solution.cpp @@ -0,0 +1,47 @@ +// https://leetcode.com/problems/sum-of-unique-elements/ + +//Test cases + +// Example 1: +// Input: nums = [1,2,3,2] +// Output: 4 +// Explanation: The unique elements are [1,3], and the sum is 4. + +// Example 2: +// Input: nums = [1,1,1,1,1] +// Output: 0 +// Explanation: There are no unique elements, and the sum is 0. + +// Example 3: +// Input: nums = [1,2,3,4,5] +// Output: 15 +// Explanation: The unique elements are [1,2,3,4,5], and the sum is 15. + +// Approach +/* +We will create an array of 101 elements, all sets to 0 and proceed to store the frequency there. + +Despite looping through 100 elements at each run to update result in the second loop. +*/ + +// Code +class Solution +{ +public: + int sumOfUnique(vector &nums) + { + // support variables + int result = 0, arr[101] = {}; + // parsing nums + for (int n : nums) + { + arr[n]++; + } + // updating result + for (int i = 1; i < 101; i++) + { + result += arr[i] == 1 ? i : 0; + } + return result; + } +};