双11众多商品进行打折销售,小明想购买一些自己心意的商品 但由于受购买资金限制,所以他决定从众多心意商品中购买3件 而且想尽可能的花完资金 现在请你设计一个程序帮助小明计算尽可能花费的最大资金额

// 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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值