|
|
|
|
|
|
g******y 发帖数: 143 | 1 Consider N coins aligned in a row. Each coin is showing either heads or
tails. The adjacency of these coins is the number of adjacent pairs of coins
with the same side facing up.
It must return the maximum possible adjacency that can be obtained by
reversing exactly one coin (that is, one of the coins must be reversed).
Consecutive elements of array A represent consecutive coins in the row.
Array A contains only 0s and/or 1s: 0 represents a coin with heads facing up
; 1 represents a coin with tails facing up. For example, given array A
consisting of six numbers, such that:
A[0] = 1
A[1] = 1
A[2] = 0
A[3] = 1
A[4] = 0
A[5] = 0
the function should return 4. The initial adjacency is 2, as there are two
pairs of adjacent coins with the same side facing up, namely (0, 1) and (4,
5). After reversing the coin represented by A[2], the adjacency equals 4, as
there are four pairs of adjacent coins with the same side facing up, namely
higher adjacency. The same adjacency can be obtained by reversing the coin
represented by A[3].
I should mention here that number of elements can be from 1....10'000. And
it has to be done as O(N) | y**********a 发帖数: 824 | 2 int longestConsecutiveCoins(boolean[]A) {
int n=A.length;
if (n<=1) return n;
int[] f=new int[n], b=new int[n]; f[0]=1; b[n-1]=1;
for (int i=1;i
f[i]=A[i]==A[i-1]?f[i-1]+1:1;
b[n-i-1]=A[i]==A[i+1]?b[n-i]+1:1;
}
int rel=0;
for (int i=1;i
rel=Math.max(rel, 1+(!A[i]==A[i-1]?f[i-1]:0)+
(!A[i]==A[i+1]?b[i+1]:0));
if (!A[0]==A[1]) rel=Math.max(rel, 1+b[1]);
if (!A[n-1]==A[n-2]) rel=Math.max(rel, f[n-2]+1);
return rel;
} | g******y 发帖数: 143 | 3 The additional space is not allowed.
【在 y**********a 的大作中提到】 : int longestConsecutiveCoins(boolean[]A) { : int n=A.length; : if (n<=1) return n; : int[] f=new int[n], b=new int[n]; f[0]=1; b[n-1]=1; : for (int i=1;i: f[i]=A[i]==A[i-1]?f[i-1]+1:1; : b[n-i-1]=A[i]==A[i+1]?b[n-i]+1:1; : } : int rel=0; : for (int i=1;i
| s*i 发帖数: 5025 | 4 Java,space 是O(1) time O(n)
coins
up
【在 g******y 的大作中提到】 : Consider N coins aligned in a row. Each coin is showing either heads or : tails. The adjacency of these coins is the number of adjacent pairs of coins : with the same side facing up. : It must return the maximum possible adjacency that can be obtained by : reversing exactly one coin (that is, one of the coins must be reversed). : Consecutive elements of array A represent consecutive coins in the row. : Array A contains only 0s and/or 1s: 0 represents a coin with heads facing up : ; 1 represents a coin with tails facing up. For example, given array A : consisting of six numbers, such that: : A[0] = 1
| a*****y 发帖数: 22 | 5 我觉得是不是可以用贪心?
只要匹配到一组 101或010的模式,把中间的那个改掉就好了。
如果匹配不到,就将一组1与0的分界点取反;如果还找不到(全0或全1的情况),就把
左边界或右边界中的一个改掉。 | r*****3 发帖数: 27 | 6 贪心应该可以吧
先扫一遍, 一共有多少adjacency = x
尝试翻任意一个i, 看他带来的变化是多少, 可能是负的, 然后保存最大变化y, 比如最
左端如果是 00 就是-1
中间010或者101就是 +2, 001就是 0, 等等
最后结果返回x+y |
|
|
|
|
|
|