LintCode "Maximum Subarray III" !
2015-10-28 04:27
369 查看
Such a classic DP.. Thought flow:
1. find out the 2 vars in the problem statement: n and k
2. setup dp equation - my first thought was by n which was not natural, so by k.
3. details: if lower inx affects higher one, we calculate from higher to lower to avoid duplicate calculation.
1. find out the 2 vars in the problem statement: n and k
2. setup dp equation - my first thought was by n which was not natural, so by k.
3. details: if lower inx affects higher one, we calculate from higher to lower to avoid duplicate calculation.
class Solution { public: /** * @param nums: A list of integers * @param k: An integer denote to find k non-overlapping subarrays * @return: An integer denote the sum of max k non-overlapping subarrays */ int maxSubArray(vector<int> nums, int k) { int n = nums.size(); if (n < k) return 0; vector<vector<int>> dp(n + 1, vector<int>(k + 1, INT_MIN)); // Init with Group 0 for(int i = 0; i <= n; i ++) dp[i][0] = 0; // DP: from Group k-1 to Group k for (int sub = 1; sub <= k; sub++) for (int i = sub; i <= nums.size(); i++) { long long rsum = INT_MIN; long long csum = 0; // NOTE: has to be from right to left - avoid duplicated calculation // because dp[j][*] -> dp[i][*] where j < i for (int j = i - 1; j >= sub - 1; j--) { csum = max((long long)nums[j], csum + nums[j]); rsum = max(rsum, csum); dp[i][sub] = max(dp[j][sub-1] + rsum, (long long)dp[i][sub]); } } return dp [k]; } };
相关文章推荐
- Quote comes from C. Joybell C.
- 4.6 Successor
- [Angular 2] Using Pipes to Filter Data
- 最大流 Ford Fulkerson, EK, SAP
- [Angular 2] Controlling how Styles are Shared with View Encapsulation
- LeetCode, Single Number
- Find Median from Data Stream 解答
- Oracle11g 遇到的一个ORA-00600[kcratr_scan_lastbwr]错误处理
- [Angular 2] ng-class and Encapsulated Component Styles
- linux不能执行命令
- Ubuntu网卡配置
- “su”和“su -”的不同
- linux软链接和硬链接
- tar 压缩时忽略目录结构
- 修复Windows XP/2003 系统TCP/IP网络协议
- 计算机的启动过程(详细)
- 在Linux中怎样配置辅DNS
- top 显示CPU所有核心信息
- linux下logrotate 配置和理解
- 靠谱:CentOS 6.4下安装Oracle 11gR2(x64)