[C++]two Methods Prefix and suffix arrays and prefix + DP
\nclass Solution {\npublic:\n    int minSumOfLengths(vector<int>& nums, int k) {\n        int n = nums.size(), res = INT_MAX;\n        int best_so_far = INT_MAX
```\nclass Solution {\npublic:\n    int minSumOfLengths(vector<int>& nums, int k) {\n        int n = nums.size(), res = INT_MAX;\n        int best_so_far = INT_MAX;\n        vector<int> left(n + 1, INT_MAX), right(n, INT_MAX);\n        int i = 0, pref = 0;\n        for(int j=0; j<n; j++) {\n            pref += nums[j];\n            while(pref > k) {\n                pref -= nums[i++];\n            }\n            if(pref == k) {\n                best_so_far = min(best_so_far, j - i + 1);\n            }\n            left[j+1] = best_so_far;\n        }\n        i = n-1; best_so_far = INT_MAX;\n        int suff = 0;\n        for(int j=n-1; j>=0; j--) {\n            suff += nums[j];\n            while(suff > k) {\n                suff -= nums[i--];\n            }\n            if(suff == k) {\n                best_so_far = min(best_so_far, i - j + 1);\n            }\n            right[j] = best_so_far;\n        }\n        for(int i=0; i<n; i++) {\n            res = min((long)res, (long)left[i] + right[i]);\n        }\n        return res == INT_MAX ? -1 : res;\n    }\n};\n```\nDP and prefix\n```\nclass Solution {\npublic:\n    int minSumOfLengths(vector<int>& nums, int k) {\n        int n = nums.size(), res = INT_MAX;\n        int pref = 0, best_so_far = INT_MAX;\n        vector<int> dp(n, INT_MAX);\n        int i = 0;\n        for(int j=0; j<n; j++) {\n            pref += nums[j];\n            while(pref > k) {\n                pref -= nums[i++];\n            }\n            if(pref == k) {\n                if(i > 0 && dp[i-1] != INT_MAX)\n                    res = min(res, dp[i-1] + j-i+1);\n                best_so_far = min(best_so_far, j - i + 1);\n            }\n            dp[j] = best_so_far;\n        }\n        return res == INT_MAX ? -1 : res;\n    }\n};\n```
['Dynamic Programming', 'Suffix Array', 'Prefix Sum']