C++ 算法:从 N 个正整数中选出 3 个和最大的数,使其总和不超过 M
#include\x20
using\x20namespace\x20std;
int\x20main()\x20{ \x20\x20int\x20N,M; \x20\x20cin\x20>>\x20N\x20>>\x20M;
\x20\x20vector
\x20\x20sort(nums.begin(),\x20nums.end());
\x20\x20int\x20maxSum\x20=\x200; \x20\x20for\x20(int\x20i\x20=\x20N-1;\x20i\x20>=\x202;\x20i--)\x20{ \x20\x20\x20\x20int\x20left\x20=\x200,right\x20=\x20i-1; \x20\x20\x20\x20while\x20(left\x20<\x20right)\x20{ \x20\x20\x20\x20\x20\x20int\x20sum\x20=\x20nums[left]\x20+\x20nums[right]\x20+\x20nums[i]; \x20\x20\x20\x20\x20\x20if\x20(sum\x20<=\x20M)\x20{ \x20\x20\x20\x20\x20\x20\x20\x20maxSum\x20=\x20max(maxSum,sum); \x20\x20\x20\x20\x20\x20\x20\x20left++; \x20\x20\x20\x20\x20\x20}else\x20{ \x20\x20\x20\x20\x20\x20\x20\x20right--; \x20\x20\x20\x20\x20\x20} \x20\x20\x20\x20} \x20\x20}
\x20\x20cout\x20<<\x20maxSum\x20<<\x20endl;
\x20\x20return\x200; }
原文地址: https://www.cveoy.top/t/topic/qhS3 著作权归作者所有。请勿转载和采集!