Word Wrap Problem

Question

    int solveWordWrap(vector<int>nums, int k) 
    { 
        // Code here
        int n = nums.size();
        vector<vector<int>> adj;
        int k_tmp = k-1; vector<int> vec;
        for(int i=0; i<n; i++){
            vec.clear(); k_tmp = k-1;
            while(i<n && k_tmp>0){
                if(nums[i]+1 < k_tmp){
                    
                    k_tmp -= nums[i]+1;
                    vec.push_back(nums[i]);
                
                }else if(nums[i] <= k_tmp){
                    
                    k_tmp -= nums[i];
                    vec.push_back(nums[i]);
                    
                }else {
                    break;
                }
                i++;
            }
            i--;
            adj.push_back(vec);
        }
        int ans=0;
        for(int i=0; i<adj.size(); i++){
            int tmp=0;
            for(int x:adj[i]){
                tmp += x;
            }
            tmp += adj[i].size()-1;
            if(i != adj.size()-1) ans += (k-tmp)*(k-tmp);
        }
        return ans;
    } 
};

Can someone tell where I am going wrong

5
6 6 7 4 4
9

I am getting 47 and I think that’s the valid answer but the right answer is 22.

@suman_18733097 Can you suggest where I am wrong in this

Optimal ordering would be

6 _ _ _ (number of extra spaces = 3)
6 _ _ _ (number of extra spaces = 3)
7 _ _   (number of extra spaces = 2)
4 _ 4   (number of extra spaces = 0
         because we are allowed to put
         one space between adjacent words)

Total Cost = 3^2 + 3^2 + 2^2 = 9 + 9 + 4 = 22. I may be wrong too.