1007. Maximum Subsequence Sum (25)
2015-11-04 12:29
351 查看
1.注意判断全为负数的情况,第一个数是否为负数,不要漏判断
2.实际上采用动态规划,dp[i]=max{dp[i-1]+num[i],num[i]},dp[i]一定会包含当前的数字num[i],但是可以简化为判断dp[i-1]是否为负数
2.实际上采用动态规划,dp[i]=max{dp[i-1]+num[i],num[i]},dp[i]一定会包含当前的数字num[i],但是可以简化为判断dp[i-1]是否为负数
//#include<string> //#include <iomanip> #include<vector> #include <algorithm> //#include<stack> #include<set> #include<queue> #include<map> //#include<unordered_set> //#include<unordered_map> //#include <sstream> //#include "func.h" //#include <list> #include<stdio.h> #include<iostream> #include<string> #include<memory.h> using namespace std; int main(void) { int n; cin >> n; if (n == 0) { cout << "0 0 0" << endl; return 0; } long long *num = new long long ; for (int i = 0; i < n; i++) { cin >> num[i]; } vector<pair<int, long long>> dp(n, { 0, 0 }); dp[0].first = 0; dp[0].second = num[0]; bool negative = true; if (num[0] >= 0) negative = false;//注意第一个数也要判断正负 for (int i = 1; i < n; i++) { if (negative&&num[i] >= 0) negative = false;//判断是否全负数 if (dp[i - 1].second <= 0) { dp[i].first = i; dp[i].second = num[i]; } else { dp[i].first = dp[i - 1].first; dp[i].second = dp[i - 1].second + num[i]; } } if (negative) { cout << 0 << " " << num[0] << " " << num[n - 1] << endl; } else { long long maxAns = -1; int index = -1; for (int i = 0; i < n; i++) { if (maxAns < dp[i].second) { maxAns = dp[i].second; index = i; } } cout << dp[index].second << " " << num[dp[index].first] << " " << num[index] << endl; } return 0; }
相关文章推荐
- UIImage存为本地文件与UIImage转换为NSData
- sqlserver中GUID的默认值设置
- leetcode-Longest Increasing Subsequence
- UIButton的图文混排
- 应用Druid进行数据源、SQL、Web应用、URI、Session等监控的简单实现
- Ignoring query to other database
- 10个顶级的CSS UI开源框架
- Invalid byte 1 of 1-byte UTF-8 sequence.解决办法
- 利用UILabel、UITextView加载html文本
- 浅谈jquey 中queue队列
- UIButton添加block点击事件
- Unique Paths II - LeetCode
- iOS 开发,UITableViewController中手势关闭cell中的键盘。且不影响tableView中的 didSelectRowAtIndexPath 方法。
- EasyUI form success IE
- Queue AbstractQueue Deque 源代码
- UIbutton文字相关
- UISlider自定义总结
- 自定义UitableViewcell 加载大图片的内存优化问题
- swagger-ui教程-构建api接口文档工具
- Android设计模式源码解析之Builder模式