【刷题篇】贪心算法(一)

文章目录

分割平衡字符串

cpp 复制代码
class Solution {
public:
    int balancedStringSplit(string s) {
        int len=s.size();
        int cnt=0;
        int balance=0;
        for(int i=0;i<len;i++)
        {
            if(s[i]=='R')
            {
                balance--;
            }
            else
            {
                balance++;
            }
            if(balance==0)
            {
                cnt++;
            }
        }
        return cnt;
    }
};

买卖股票的最佳时机Ⅱ

cpp 复制代码
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int maxprofit=0;
        int day=prices.size();
        for(int i=1;i<day;i++)
        {
            if(prices[i-1]<prices[i])
            {
                maxprofit+=prices[i]-prices[i-1];
            }
        }
        return maxprofit;
    }
};

跳跃游戏

cpp 复制代码
class Solution {
public:
    bool canJump(vector<int>& nums) {
        int maxlen=0;
        int len=nums.size();
        for(int i=0;i<len;i++)
        {   //判断是否能到当前位置
            if(maxlen>=i)
            {
                maxlen=max(maxlen,i+nums[i]);
            }
            else
            {   //到不了当前位置就说明也就到不了最后的位置
                return false;
            }
            //当最大路径大于总里程时就可以返回了
            if(maxlen>len-1)
            {
                return true;
            }
        }
        return true;
    }
};

钱币找零

假设1元、2元、5元、10元、20元、50元、100元的纸币分别由c0,c1,c2,c3,c4,c5,c6张。现在要用这些钱来支付K元,至少要用多少张纸币?

cpp 复制代码
#include<iostream>
#include<algorithm>
#include<vector>

using namespace std;

struct moneycmp
{
	bool operator()(vector<int>& array1, vector<int>& array2)
	{
		return array1[0] > array2[0];
	}
}cmp;
//0:是面值  1:是数量
int MoneyMat(vector<vector<int>>& moneymat, int money)
{
	int cnt = 0;
	sort(moneymat.begin(),moneymat.end(),cmp);
	//遍历面值
	for (auto& array : moneymat)
	{
		int c = 0;
		c = money / array[0];
		//确保取得是最小值,保证张数不会超
		c=min(c, array[1]);
		money -= c * array[0];
		cnt += c;
	}
	if (money != 0)
	{
		return -1;
	}
	return cnt;
}

int main()
{                              //面值,数量
	vector<vector<int>> mat = { {100,5} ,{50,3},{20,4},{5,5},{2,5},{1,10} };
	int money=0;
	cin >> money;
	int count=MoneyMat(mat,money);
	cout << count << endl;
	return 0;
}
相关推荐
vibecoding日记2 小时前
双非如何快速入职字节等大厂大模型?真实案例分析:推理优化和投机解码
算法·求职·大模型工程师
yszaygr21384 小时前
Verilog参数化游程编码RLE模块
算法
望易4 小时前
刚设计的大模型架构-双域耦合认知框架
算法·架构
复杂网络8 小时前
多个 Claude Code 与多个 Codex 协同工作:设计与实现方案
算法
apocelipes1 天前
常用编程语言和库的正则表达式性能对比
c语言·c++·python·性能优化·golang·开发工具和环境
HjhIron1 天前
面试常客:字符串算法从入门到进阶
算法·面试
吴佳浩1 天前
DeepSeek DSpark:Confidence-Scheduled Speculative Decoding 技术解析
人工智能·算法·deepseek
触底反弹1 天前
🧠 搞懂 Token,才算真正入门大模型——从分词原理到 Embedding 语义实战
javascript·人工智能·算法
vivo互联网技术1 天前
ICLR 2026 | 基于后验采样的图像恢复方法LearnIR:人脸去阴影、去雾
人工智能·算法·aigc
浮生望1 天前
JS字符串与回文算法:从包装类到双指针的面试进阶之路
javascript·算法