Question

Given an array of non-negative integers. Find the largest multiple of 3 that can be formed from array elements.

For example, if the input array is {8, 1, 9}, the output should be “9 8 1″, and if the input array is {8, 1, 7, 6, 0}, output should be “8 7 6 0″.

Solution

A number is multiple of 3 if and only if the sum of digits of number is multiple of 3.

1. Sort the array in non-decreasing order.

2. Take three queues. One for storing elements which on dividing by 3 gives remainder as 0.The second queue stores digits which on dividing by 3 gives remainder as 1. The third queue stores digits which on dividing by 3 gives remainder as 2. Call them as queue0, queue1 and queue2

3. Find the sum of all the digits.

4. Three cases arise:
……4.1 The sum of digits is divisible by 3. Dequeue all the digits from the three queues. Sort them in non-increasing order. Output the array. ……4.2 The sum of digits produces remainder 1 when divided by 3.
Remove one item from queue1. If queue1 is empty, remove two items from queue2. If queue2 contains less than two items, the number is not possible. ……4.3 The sum of digits produces remainder 2 when divided by 3.
Remove one item from queue2. If queue2 is empty, remove two items from queue1. If queue1 contains less than two items, the number is not possible. 5. Finally empty all the queues into an auxiliary array. Sort the auxiliary array in non-increasing order. Output the auxiliary array.

最新文章

  1. bootstrap学习笔记--bootstrap组件
  2. QT 对话框二
  3. 如何开发 Sublime Text 2 的插件
  4. 学习iOS笔记第一天的C语言学习记录
  5. X-UA-Compatible设置兼容模式
  6. Objc基础学习记录5
  7. LVS的调度算法分析
  8. [原创] linux 下上传 datapoint数据到yeelink 【golang版本】
  9. 生产者/消费者问题的多种Java实现方式
  10. jsp 表单回显
  11. mui返回上个页面并刷新数据
  12. HashMap 1.7
  13. Android 基础 十一 Android的消息机制
  14. CTF中图片隐藏文件分离方法
  15. 个人对java中对象锁与类锁的一些理解与实例
  16. 关于UrlEncode 一团乱麻的问题,后续彻底理解。Java中的 URLEncoder 与 URLDecoder无bug
  17. Transaction ACID (转载)
  18. 贪心--cf、education62-C
  19. hibernate3的配置
  20. scp命令详解—跨服务器复制文件

热门文章

  1. Mac下配置phpredis扩展
  2. 360网站卫士常用前端公共库CDN服务
  3. c语言输出可见字符
  4. 7 个改变世界的 Java 项目
  5. MongoDB 操作手冊CRUD插入
  6. 多封装,少开放。强烈建议C++标准添加class之间的注入机制
  7. with admin option 与with grant option
  8. VCS仿真 Dump Memory
  9. (转)ie -ms-interpolation-mode: bicubic 属性详解
  10. asp.net 参数形式写sql