// test.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "iostream"
#include "string"
#include "vector"
#include "list"
#include "algorithm"
using namespace std;
// 双11众多商品进行打折销售,小明想购买一些自己心意的商品
/*但由于受购买资金限制,所以他决定从众多心意商品中购买3件
而且想尽可能的花完资金
现在请你设计一个程序帮助小明计算尽可能花费的最大资金额
输入描述
第一行为整型数组M 数组长度小于100 数组元素记录单个商品的价格
单个商品价格 < 1000
第二行输入为购买资金的额度R
R < 100000
输出描述
输出为满足上述条件的最大花费额度
如果不存在满足上述条件的商品请返回 - 1
例子1
输入
23,26,36,27
78
输出
76
例子2
输入
23,30,40
26
输出
- 1
————————————————
版权声明:本文为CSDN博主「羊族的希望」的原创文章,遵循CC 4.0 BY - SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https ://blog.csdn.net/weixin_41010318/article/details/120731158
*/
// 滑动窗口解决
vector<int> get_nums(string str)
{
vector<int> nums;
size_t pos = 0;
pos = str.find(',');
string ss;
while(pos != str.npos) {
ss = str.substr(0, pos);
str = str.substr(pos + 1, str.size() -1);
pos = str.find(',');
int m = atoi(ss.c_str());
nums.push_back(m);
}
int m = atoi(str.c_str());
nums.push_back(m);
for(auto c : nums){
cout << c << endl;
}
return nums;
}
int get_max_pay()
{
int n = 0;
int max = -1;
string str;
cin >> str;
vector<int> res;
vector<int> nums = get_nums(str);
cin >> n;
sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size() - 3; ++i) {
if (i == 0 && nums[i] >= n) {
return -1;
}
int left = i + 1;
int right = nums.size() - 1;
while (right > left) {
if (nums[i] + nums[left] + nums[right] > n) {
right--;
} else if (nums[i] + nums[left] + nums[right] <= n) {
max = max > nums[i] + nums[left] + nums[right] ? max : nums[i] + nums[left] + nums[right];
left++;
}
}
}
cout << max << endl;
return max;
}
int main()
{
get_max_pay();
system("Pause");
return 0;
}