数据结构与算法分析——c语言描述 练习2.12 答案
求最小子序列和 求最小的正序列,用了联机算法,线性复杂度
#include<stdio.h> #define MAXN 1000 int a[MAXN]; int n; int minSubsequenceSum() { int ThisSum, MinSum, i,min; ThisSum = MinSum = 0; int flag=1; min = a[0]; for (i = 0; i < n; i++) { ThisSum += a[i]; if (min > a[i]) min = a[i]; if (ThisSum < MinSum) { MinSum = ThisSum; flag = 1; } else if (ThisSum>0) ThisSum = 0; } if (flag) return MinSum; else return min; } int main() { scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", &a[i]); } printf("%d", minSubsequenceSum()); }
这道题求乘积最大一开始完全不会做,网上找了答案才知道是用动态规划。
求最大子序列乘积,用了动态规划,乘积不像加法,两个负数相乘可能会是最大的。
#include<stdio.h> #include<algorithm> using namespace std; #define MAXN 1000 int n,a[MAXN],maxA[MAXN],minA[MAXN]; int maxSubsequenceMul() { maxA[0] = minA[0] = a[0]; int ans = a[0]; for (int i = 1; i < n; i++) { maxA[i] = max(max(a[i], minA[i - 1] * a[i]), maxA[i - 1] * a[i]); minA[i] = min(min(a[i], minA[i - 1] * a[i]), maxA[i - 1] * a[i]); ans = max(ans, maxA[i]); } return ans; } int main() { scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", &a[i]); } printf("%d", maxSubsequenceMul()); }