```
public class Solution {
public int magicalString(int n) {
if(n<=0) return 0;
if(n<=3) return 1;
int[] arr = new int[n];
arr[0] = 1; arr[1]=2; arr[2] = 2;
boolean flagOne = true;
int count = 1;
for(int i=2, j=3; i<n; i++){
for(int k=0; j<n && k<arr[i]; k++, j++){
if(flagOne){
arr[j] = 1;
count++;
} else {
arr[j] = 2;
}
}
flagOne ^= true;
}
return count;
}
}
```