classSolution{public:intminSpaceWastedKResizing(vector<int>&nums,intk){vector<vector<int>>mem(nums.size(),vector<int>(k+1,-1));returnminSpaceWasted(nums,0,k,mem);}private:staticconstexprintkMax=200'000'000;// Returns the minimum space wasted for nums[i..n) if you can resize k times.intminSpaceWasted(constvector<int>&nums,inti,intk,vector<vector<int>>&mem){if(i==nums.size())return0;if(k==-1)returnkMax;if(mem[i][k]!=-1)returnmem[i][k];intres=kMax;intsum=0;intmaxNum=nums[i];for(intj=i;j<nums.size();++j){sum+=nums[j];maxNum=max(maxNum,nums[j]);constintwasted=maxNum*(j-i+1)-sum;res=min(res,minSpaceWasted(nums,j+1,k-1,mem)+wasted);}returnmem[i][k]=res;}};
classSolution{publicintminSpaceWastedKResizing(int[]nums,intk){Integer[][]mem=newInteger[nums.length][k+1];returnminSpaceWasted(nums,0,k,mem);}privatestaticfinalintMAX=200_000_000;// Returns the minimum space wasted for nums[i..n) if you can resize k times.privateintminSpaceWasted(int[]nums,inti,intk,Integer[][]mem){if(i==nums.length)return0;if(k==-1)returnMAX;if(mem[i][k]!=null)returnmem[i][k];intres=MAX;intsum=0;intmaxNum=nums[i];for(intj=i;j<nums.length;++j){sum+=nums[j];maxNum=Math.max(maxNum,nums[j]);finalintwasted=maxNum*(j-i+1)-sum;res=Math.min(res,minSpaceWasted(nums,j+1,k-1,mem)+wasted);}returnmem[i][k]=res;}}
classSolution:defminSpaceWastedKResizing(self,nums:list[int],k:int)->int:MAX=200_000_000@functools.lru_cache(None)defdp(i:int,k:int)->int:""" Returns the minimum space wasted for nums[i..n) if you can resize k times. """ifi==len(nums):return0ifk==-1:returnMAXres=MAXsumm=0maxNum=nums[i]forjinrange(i,len(nums)):summ+=nums[j]maxNum=max(maxNum,nums[j])wasted=maxNum*(j-i+1)-summres=min(res,dp(j+1,k-1)+wasted)returnresreturndp(0,k)
Thanks for stopping by! If you find this site helpful, consider buying me some protein powder to keep me fueled! π