[牛客网算法笔记]分糖果问题
来源:互联网 发布:注册淘宝网店铺流程 编辑:程序博客网 时间:2024/06/11 08:17
【左神】
【问题描述】
【基础】
1.每个孩子不管得分多少,最少分到一个糖果。
2.任意两个相邻的孩子之间,得分较多的孩子必须拿多一些的糖果
根据左讲解的坡度我们来理解一下。见下图
大概思想应该是这样。代码我拷贝的别人的,图是我自己理解的。可以复制代码看一看。
public class Problem_07_CandyProblem {public static int candy1(int[] arr) {if (arr == null || arr.length == 0) {return 0;}int index = nextMinIndex1(arr, 0);int res = rightCands(arr, 0, index++);int lbase = 1;int next = 0;int rcands = 0;int rbase = 0;while (index != arr.length) {if (arr[index] > arr[index - 1]) {res += ++lbase;index++;} else if (arr[index] < arr[index - 1]) {next = nextMinIndex1(arr, index - 1);rcands = rightCands(arr, index - 1, next++);rbase = next - index + 1;res += rcands + (rbase > lbase ? -lbase : -rbase);lbase = 1;index = next;} else {res += 1;lbase = 1;index++;}}return res;}public static int nextMinIndex1(int[] arr, int start) {for (int i = start; i != arr.length - 1; i++) {if (arr[i] <= arr[i + 1]) {return i;}}return arr.length - 1;}public static int rightCands(int[] arr, int left, int right) {int n = right - left + 1;return n + n * (n - 1) / 2;}public static int candy2(int[] arr) {if (arr == null || arr.length == 0) {return 0;}int index = nextMinIndex2(arr, 0);int[] data = rightCandsAndBase(arr, 0, index++);int res = data[0];int lbase = 1;int same = 1;int next = 0;while (index != arr.length) {if (arr[index] > arr[index - 1]) {res += ++lbase;same = 1;index++;} else if (arr[index] < arr[index - 1]) {next = nextMinIndex2(arr, index - 1);data = rightCandsAndBase(arr, index - 1, next++);if (data[1] <= lbase) {res += data[0] - data[1];} else {res += -lbase * same + data[0] - data[1] + data[1] * same;}index = next;lbase = 1;same = 1;} else {res += lbase;same++;index++;}}return res;}public static int nextMinIndex2(int[] arr, int start) {for (int i = start; i != arr.length - 1; i++) {if (arr[i] < arr[i + 1]) {return i;}}return arr.length - 1;}public static int[] rightCandsAndBase(int[] arr, int left, int right) {int base = 1;int cands = 1;for (int i = right - 1; i >= left; i--) {if (arr[i] == arr[i + 1]) {cands += base;} else {cands += ++base;}}return new int[] { cands, base };}public static void main(String[] args) {int[] test1 = { 3, 0, 5, 5, 4, 4, 0 };System.out.println(candy1(test1));int[] test2 = { 3, 0, 5, 5, 4, 4, 0 };System.out.println(candy2(test2));}}
阅读全文
0 0
- [牛客网算法笔记]分糖果问题
- 算法题:分糖果
- 分糖果问题
- 分糖果问题1
- 分糖果 问题
- 分糖果问题
- 分糖果问题--蓝桥杯
- 问题 1431: 分糖果
- 站队问题、分糖果问题
- 贪心算法之分糖果
- OJ-Candy 分糖果问题
- 分糖果问题(java)
- 其他题目---分糖果问题
- 分糖果(图论算法)
- 蓝桥-分糖果(算法训练)
- leetcode 135. Candy 分糖果 + 贪心算法
- [LeetCode]—Candy 分糖果问题
- LeetCode | Candy(分糖果问题)
- Delphi匿名方法
- 关于char, wchar_t, TCHAR, _T,L,TEXT,_TEXT,LPSTR,LPCSTR,PWSTR,PCWSTR,LPTSTR,LPCTSTR的区别
- linux小练习4
- 重学数据结构 链表(工程文件)算法2.8 2.9 2.10 2.11
- 例2.1b
- [牛客网算法笔记]分糖果问题
- Openstack中说的二层和三层switch
- 练习17.10.3
- 【codevs 1135】选择客栈
- effective java(22) 之优先考虑静态成员类
- List和Set
- jdbc基础知识
- git版本控制工具使用教程(二)团队开发
- centos安装telnet服务