classSolution{public:intnumberOfGoodPartitions(vector<int>&nums){constexprintkMod=1'000'000'007;intans=1;// lastSeen[num] := the index of the last time `num` appearedunordered_map<int,int>lastSeen;for(inti=0;i<nums.size();++i)lastSeen[nums[i]]=i;// Track the maximum right index of each running partition by ensuring that// the first and last occurrences of a number fall within the same// partition.intmaxRight=0;for(inti=0;i<nums.size();++i){if(i>maxRight)// Start a new partition that starts from nums[i].// Each partition doubles the total number of good partitions.ans=(ans*2L)%kMod;maxRight=max(maxRight,lastSeen[nums[i]]);}returnans;}};
classSolution{publicintnumberOfGoodPartitions(int[]nums){finalintMOD=1_000_000_007;intans=1;// lastSeen[num] := the index of the last time `num` appearedHashMap<Integer,Integer>lastSeen=newHashMap<>();for(inti=0;i<nums.length;++i)lastSeen.put(nums[i],i);// Track the maximum right index of each running partition by ensuring that// the first and last occurrences of a number fall within the same// partition.intmaxRight=0;for(inti=0;i<nums.length;++i){if(i>maxRight)// Start a new partition that starts from nums[i].// Each partition doubles the total number of good partitions.ans=(int)((ans*2L)%MOD);maxRight=Math.max(maxRight,lastSeen.get(nums[i]));}returnans;}}
1 2 3 4 5 6 7 8 9101112131415161718192021
classSolution:defnumberOfGoodPartitions(self,nums:list[int])->int:MOD=1_000_000_007ans=1# lastSeen[num] := the index of the last time `num` appearedlastSeen={}fori,numinenumerate(nums):lastSeen[num]=i# Track the maximum right index of each running partition by ensuring that# the first and last occurrences of a number fall within the same partition.maxRight=0fori,numinenumerate(nums):ifi>maxRight:# Start a new partition that starts from nums[i].# Each partition doubles the total number of good partitions.ans=ans*2%MODmaxRight=max(maxRight,lastSeen[num])returnans