从给定的0、1和2中找出总和能被3整除的组数,并使之最大化。
- 难度等级 : 中等
- 最后更新 : 2021年8月6日
给出三个整数,C0、C1和C2,一组 S中0、1和2的频率,任务是找出总和能被3整除的最大组数,条件是**总和(S)**能被3整除,所有组的联合必须等于 S。
例子。
输入:C0 = 2, C1 = 4, C2 = 1
输出:4
解释:它可以将组S={0,0,1,1,1,1,2}分为四个组{0},{0},{1,1,1},{1,2}。可以证明,4是最大的可能答案。输入:C0 = 250, C1 = 0, C2 = 0
输出: 250
办法。这 个问题可以用 贪婪算法.按照下面的步骤来解决这个问题。
- 初始化一个变量maxAns,比如说0,用来存储最大的组数。
- 把C0加到maxAns中,因为每个**{0}**都可以是一个组,使其总和能 被3整除。
- 初始化一个变量 k,比如min(C1, C2),并把它加到maxAns中,因为至少有 k,{1, 2} 组可以被创建。
- 将abs(C1-C2)/3加到maxAns中,它将对剩余的 1或2做出贡献。
- 返回maxAns。
下面是上述方法的实现。
C++
#include <bits/stdc++.h>using namespace std;int maxGroup(int c0,int c1,int c2){// Initalizing to store maximum number of groupsint maxAns = 0;// Adding C0maxAns += c0;// Taking Minimum of c1, c2 as minimum number of// pairs must be minimum of c1, c2int k = min(c1, c2);maxAns += k;// If there is any remaining element in c1 or c2// then it must be the absolute difference of c1 and// c2 and dividing it by 3 to make it one pairmaxAns +=abs(c1 - c2) / 3;return maxAns;}int main(){int C0 = 2, C1 = 4, C2 = 1;cout << maxGroup(C0, C1, C2);return 0;}// This code is contributed by maddler |
爪哇
// Java program for above appraochimport java.io.*;class GFG {// Function to calculate maximum number of groupspublic static int maxGroup(int c0,int c1,int c2){// Initalizing to store maximum number of groupsint maxAns =0;// Adding C0maxAns += c0;// Taking Minimum of c1, c2 as minimum number of// pairs must be minimum of c1, c2int k = Math.min(c1, c2);maxAns += k;// If there is any remaining element in c1 or c2// then it must be the absolute difference of c1 and// c2 and dividing it by 3 to make it one pairmaxAns += Math.abs(c1 - c2) /3;return maxAns;}// Driver Codepublic static void main(String[] args){// Given Inputint C0 =2, C1 =4, C2 =1;// Function CallSystem.out.println(maxGroup(C0, C1, C2));}} |
输出。
4
_时间复杂度。_O(1)
辅助空间。 O(1)
读者请注意!现在不要停止学习。掌握所有重要的DSA概念。 DSA自学课程以适合学生的价格获得所有重要的DSA概念,并成为行业的准备者。 要完成从学习语言到DS Algo以及更多的准备工作,请参考 完整的面试准备课程.
如果你想参加专家的现场课程 ,请参考 面向在职人士的DSA现场课程 和 面向学生的竞争性编程直播课程.
我的个人笔记 arrow_drop_up
拯救