"use strict";
process.stdin.resume();
process.stdin.setEncoding("utf-8");

let inputString = "";
let currentLine = 0;

process.stdin.on("data", (inputStdin) => {
  inputString += inputStdin;
});
process.stdin.on("end", () => {
  inputString = inputString.split("\n");
  main();
});
function readline() {
  return inputString[currentLine++];
}

function main() {
  var t = +(readline());
  while (t--) {
    solution();
  }
}

function solution() {
  const n = +(readline());
  const str = readline();

  let ans = 0;
  for (let i = 0; i < n-1; i++) {
    let s = (str[i] === '0') ? 0 : +str[i]+1;
    ans+=s;
  }
  ans += +str[n-1];
  console.log(ans);
}

function isPrime(num) {
  if (num === 2) return true;
    if (num === 1 || num%2 === 0 ) return false;

    let root = Math.floor(Math.sqrt(num));
    root += (root%2)-1;
    while (root > 1) {
      if (num%root === 0)
        return false;
      root -= 2;
    }
    return true;
}

let stop = '';
process.stdin.on('data', c => stop += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = stop.split(EOL);
	var t = lines[0];
	var n = 0;
	for(i = 1; i <= t * 2; i++){
        if(i % 2 == 1){
            n = lines[i];
        }else{
            var s = lines[i].split('').map(Number);
            var ans = s[n - 1];
            for(j = 0; j < n - 1; j++){
                if(s[j] !== 0){
                    ans += (s[j]) + 1;
                }
            }
            console.log(ans);
        }
	}
});

//https://codeforces.com/problemset/problem/1573/A?locale=en
process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main(inputString);
});

function log(message) {
    if (process.env.NODE_ENV === "debug") {
        console.log(message);
    }
}

function calculateStepsNeededFor0(digits) {
    const digitProcessor = (accumulator, currentValue, currentIndex) => {
        const costOfMoving = 1;
        const isLastDigit = currentIndex === digits.length-1;

        if(isLastDigit){
            return accumulator + currentValue;
        }else{
            if(currentValue === 0){
                return accumulator
            }else{
                return accumulator + currentValue + costOfMoving;
            }
        }
    }

    const allNumbersSummarised = String(digits)
        .split("")
        .map(x => Number(x))
        .reduce(digitProcessor, 0);

    return allNumbersSummarised;
}

function main(fileContents) {//input lines as an array
    // console.log(fileContents);
    const header = fileContents.splice(0, 1);
    const tasksWithoutLength = fileContents.filter((elem, id) => id % 2 !== 0)

    const clockTransformationSteps = tasksWithoutLength
        .map(calculateStepsNeededFor0);

    //PrintOutput
    clockTransformationSteps.forEach((x) => console.log(x))
}

let data = '';
process.stdin.on('data', c => data += c);

function* nextLine() {
	let lines = data.trim().split(/\n/g);
	for(let l of lines){
		yield l.trim();
	}
}

let nl = nextLine();

nl.elem = function(funParse) {
		return funParse(this.next().value);
	};

nl.array = function(funParse) {
		return this.next().value.split(/\s/g).map(funParse||(x => x));
	};

nl.num = function() {
		return nl.elem(Number);
	};

nl.nums = function() {
		return nl.array(Number);
	};

nl.line = function() {
		return this.next().value;
	};

const sol = () => {
	//your code this
	let t = nl.num();
	let ans = [];
	for(let i = 0; i < t; i++){
		let n = nl.num();
		let s = nl.line();
		let r = 0;
		for(let j = n - 1; j >= 0; j--){
			let x = Number(s.charAt(j));
			if (x > 0) {
				r += x;
				if (j < n-1) {
					r++;
				}
			}
		}
		ans.push(r);
	}
	console.log(ans.join('\n'));
};

process.stdin.on('end', sol);

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
	input: process.stdin, output: process.stdout
});
var obj; var inLine = []; var outputList = [];var retcode = new Set();
read.on('line', function(input){
	var tmp = input.split(' ');
	for(var i = 0; i < tmp.length; i++){
		inLine.push(tmp[i]);
		if(i == tmp.length - 1){
			retcode.add(inLine.length);
		}
	}
});
read.on('close', function(){
	obj = init(inLine);
	console.error('\n↑入力 ↓出力');
	Main();
	console.log(myconv(outputList, 9));
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextArray(size, code){
	var ret = new Array(size);
	for(var i = 0; i < size; i++){
		if(code == 'int'){
			ret[i] = nextInt();
		}else if(code == 'long'){
			ret[i] = BigInt(next());
		}else{
			ret[i] = next();
		}
	}
	return ret;
}
function nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');}
function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());}
function getCountMap(list){
	var map = {};
	for(var i = 0; i < list.length; i++){
		if(map[list[i]] == null){
			map[list[i]] = 0;
		}
		map[list[i]]++;
	}
	return map;
}
function init(input){
	return {
		list : input, index : 0, max : input.length,
		hasNext : function(){return (this.index < this.max);},
		next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},
		isReturn : function(){return retcode.has(this.index);}
	};
}
function myout(s){outputList.push(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
function isReturn(){return obj.isReturn();}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	while(hasNext()){
		var N = nextInt();
		var s = next();
		var output = 0;
		for(var i = 0; i < N; i++){
			var v = myconv(s[i], 1);
			if(v > 0){
				if(i < N - 1){
					output += v + 1;
				}else{
					output += v;
				}
			}

		}
		myout(output);
	}
}

const readline = require('readline')

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input)
})
rl.on('close', () => {
    let l = 0
    let t = lines[l++]
    for (let i = 0; i < t; i++) {
        const n = lines[l++]
        const str = lines[l++].trim().split('').reverse()
        console.log(solve(str))
    }
})

function solve(str) {
    let count=0
    for(let j=0;j<str.length;j++){
        const digit=Number(str[j])
        if(j!==0){
            if(digit!==0) count=count+1
        }
        count=count+digit
    }
    return count;
}

const nextString = (function() {
  const listeners = [], strings = [], ps = process.stdin
  let last = ''
  ps.setEncoding('utf8')
  ps.on('readable', () => {
    let chunk
    while ((chunk = ps.read()) !== null) {
      chunk = (last + chunk).split(/\r\n|\r|\n/)
      last = chunk[chunk.length - 1]
      for (let i = 0; i < chunk.length - 1; ++i) {
        if (chunk[i].length > 0) {
          if (listeners.length > 0) {
            listeners.shift()(chunk[i])
          }
          else {
            strings.push(chunk[i])
          }
        }
      }
    }
  })
  const fn = resolve => {
    if (strings.length > 0) {
      resolve(strings.shift())
    }
    else {
      listeners.push(resolve)
    }
  }
  return () => new Promise(fn)
})()

async function main() {
  let t = +await nextString()
  for (let iii = 0; iii < t; ++iii) {
    let n = +await nextString()
    let mas = (await nextString()).split('').map(char => +char)
    let ans = 0
    ans += mas[mas.length - 1]
    mas[mas.length - 1] = 0
    while (true) {
      let p = 0
      while (p < mas.length && mas[p] === 0) {
        ++p
      }
      if (p === mas.length) {
        break
      }
      let temp = mas[p]
      mas[p] = mas[n - 1]
      mas[n - 1] = temp
      ans += mas[n - 1]
      mas[n - 1] = 0
      ++ans
    }
    console.log(ans)
  }
}

main()

function main() {
     var no_of_inputs = readline()
     for(var i=0;i<no_of_inputs;i++) {
          var length = readline()
          var time = readline()
          var count = 0
          for(var j=0;j<time.length;j++) {
               if(j == time.length-1) {
                    count += parseInt(time[j])
               } else if(time[j] != 0){
                    count += 1+parseInt(time[j])
                     }
               }
          print(count)
          }
}
main()

const readline = require('readline')
function solve(s1)
{
    n = s1.length;
    let res = 0;
    for(let i=0;i<n;i++)
    {
        res += parseInt(s1[i]);
        if(s1[i]!='0'&&(i!=n-1))
        {
            res += 1;
        }

    }
    return res;
}
var n;

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input)
})
rl.on('close', () => {
    let l = 0
    let t = lines[l++]
    for (let i = 0; i < t; i++) {
        const n = lines[l++]
        const str = lines[l++].trim().split('')
        console.log(solve(str))
    }
})
// var n = readLine();
// var in1 = readLine();
// console.log(solve(in1,parseInt(n)));

const readline = require('readline')
function solve(s1)
{
    n = s1.length;
    let res = 0;
    for(let i=0;i<n;i++)
    {
        res += parseInt(s1[i]);
        if(s1[i]!='0'&&(i!=n-1))
        {
            res += 1;
        }

    }
    return res;
}
var n;

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input)
})
rl.on('close', () => {
    let l = 0
    let t = lines[l++]
    for (let i = 0; i < t; i++) {
        const n = lines[l++]
        const str = lines[l++].trim().split('').reverse()
        console.log(solve(str))
    }
})
// var n = readLine();
// var in1 = readLine();
// console.log(solve(in1,parseInt(n)));

const readline = require('readline')
function solve(s1)
{
    n = s1.length;
    let res = 0;
    for(let i=0;i<n;i++)
    {
        res += parseInt(s1[i]);
        if(s1[i]!='0')
        {
            res += 1;
        }

    }
    return res-1;
}
var n;

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input)
})
rl.on('close', () => {
    let l = 0
    let t = lines[l++]
    for (let i = 0; i < t; i++) {
        const n = lines[l++]
        const str = lines[l++].trim().split('').reverse()
        console.log(solve(str))
    }
})
// var n = readLine();
// var in1 = readLine();
// console.log(solve(in1,parseInt(n)));

const readline = require('readline')
function solve(s1)
{
    let res = 0;
    for(let i=0;i<n;i++)
    {
        res += parseInt(s1[i]);
        if(s1[i]!='0')
        {
            res += 1;
        }

    }
    return res-1;
}
var n;

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input)
})
rl.on('close', () => {
    let l = 0
    let t = lines[l++]
    for (let i = 0; i < t; i++) {
        const n = lines[l++]
        const str = lines[l++].trim().split('').reverse()
        console.log(solve(str))
    }
})
// var n = readLine();
// var in1 = readLine();
// console.log(solve(in1,parseInt(n)));

let i = '';
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL);
    var n = lines[0];
    var e = 0;
    for(var j = 1; j <= n * 2; j++){
        if(j % 2 === 0){
            var k = lines[j].split(' ').map(Number);
            k = k.sort(function(a, b){return a - b});
            var a = [];
            for(var l = 1; l <= k.length; l++){
                if(k[l] != k[l - 1]){
                    a.push(k[l - 1]);
                }
            }
            if(a.length == 1){
                console.log(e);
            }else{
                console.log(1);
            }
        }else{
            e = lines[j];
        }
    }
});

///https://codeforces.com/problemset/problem/1452/A

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main(inputString);
});

function main(fileContents) {//input lines as an array
    const amoutOfInputsForTheProgram = fileContents.splice(0,1);
    const listOfEndpointsForRobot = [...fileContents];

    listOfEndpointsForRobot
        .map((endpoints)=>endpoints.split(" "))
        .map((endpoints)=>{
           const diffBetweetVertAndHorizontal = Math.abs(parseInt(endpoints[0])-parseInt(endpoints[1]));
           return parseInt(endpoints[0])+parseInt(endpoints[1])
               +(diffBetweetVertAndHorizontal > 0 ? (diffBetweetVertAndHorizontal-1) : 0)
        })
        .forEach(x=>console.log(x));

}


const
    verticesCount  = readline();
var
    vertices = [],
    isChristmassTree = true;
    vertices.push(0),
    levels = {},
    roots = [];
for (var i = 1; i < verticesCount; i++) {
    vertices.push(readline());
}

vertices.forEach((vert, i) => {
    if (!levels.hasOwnProperty(vert)) {
        levels[vert] = [];
    }
        levels[vert].push(i+1);

})

function checkLength(object) {
    for (var key in object) {
        if (key > 0) {
            if (object[key].length < 3) {
                isChristmassTree = false;
                break;
            }
            roots.push(key);
        }
    }
}

function checkRoots(roots) {
    roots.forEach(root => {
        for (var key in levels) {
            if (key > 0) {
               if (levels[key].includes(Number(root))) {
                  levels[key].splice(levels[key].indexOf(Number(root)), 1)
               }
            }
        }
    })
}

checkLength(levels)
if (isChristmassTree) {
checkRoots(roots)
checkLength(levels)
}

print(isChristmassTree ? 'Yes' : 'No')

var n = +readline();
//+prompt("Enter kol verwun");
var koli4estvoVerwun = [n];

var roditelInex = 0;
var dannajaVetka;
var roditelVetka;
var mainVerwuna;
var verwuna;

koli4estvoVerwun[0] = {
                      roditel: null,
                      listkov: 0,
                      esListom: true
                      }

    function findRes(data) {
for (var i = 0; i < n; i++) {
verwuna = data[i];
if (!verwuna.esListom && verwuna.listkov < 3) {
return 'No';
}
}
return 'Yes';
}

for (var i = 1; i < n; i++) {
    roditelInex = +readline() - 1;
    //+prompt("data") - 1;
    if (!koli4estvoVerwun[i]) {
        koli4estvoVerwun[i] = {
                              roditel: roditelInex,
                              listkov: 0,
                              esListom: true
                              };
    }

dannajaVetka = koli4estvoVerwun[i];

if (!koli4estvoVerwun[roditelInex]) {
    koli4estvoVerwun[roditelInex] = {
        roditel: null,
        listkov: dannajaVetka.esListom ? 1 : 0,
        esListom: false
    };
} else {

roditelVetka = koli4estvoVerwun[roditelInex];
if (roditelVetka.esListom) {
    roditelVetka.esListom = false;

    mainVerwuna = koli4estvoVerwun[roditelVetka.roditel];
    if (mainVerwuna) {
        mainVerwuna.listkov = Math.max(0 , mainVerwuna.listkov -1);
    }
}
if (dannajaVetka.esListom) {
    roditelVetka.listkov++;
}
}
}
print(findRes(koli4estvoVerwun));
//alert(findRes(koli4estvoVerwun));

var n=Number(readline())
var N=new Array(n+1)
N[1]={c:[]}
for (var i=0;i<n-1;++i) {
 var p=Number(readline())
 N[i+2]={c:[]}
 N[p].c.push(N[i+2])
}
var check=i=>{
 var l=N[i].c.length;
 if (l) {
  var cc=0;
  for (var j=0;j<l;++j)
   cc += (!N[i].c[j].c.length)
  return cc>=3;
 } else return true;
}

var a=true;
for (var i=1;i<=n;++i)
 a = a && check(i)
print(a?'Yes':'No')

function isSpruce(tree) {
    for (var i = 0; i < tree.length; i++) {
    var leaf_children = 0;
        for (var j = 1 + i; j < tree.length; j++) if (tree[j]["parent"] === i && tree[j]["isLeaf"]) leaf_children += 1;
        if (leaf_children < 3 && !tree[i].isLeaf) return "No";
    }
    return "Yes";
}

var tree = new Array(parseInt(readline()));
tree[0] = { isLeaf: true, leaf_children: 0, parent: null};

for (var i = 1; i < tree.length; i++) {
    parent_index = parseInt(readline()) - 1;
    tree[i] = { isLeaf: true, leaf_children: 0, parent: parent_index};
    tree[parent_index]["isLeaf"] = false;
    tree[parent_index]["leaf_children"] += 1;
}

print(isSpruce(tree));

function isElka(tree) {
    for (var i = 0; i < tree.length; i++) {
    var children = 0;
        for (var j = 1 + i; j < tree.length; j++) if (tree[j]["parent"] === i && tree[j]["isLeaf"]) children += 1;
        if (children < 3 && !tree[i].isLeaf) return "No";
    }
    return "Yes";
}

var res = "Yes";
var tree = new Array(parseInt(readline()));
tree[0] = { isLeaf: true, leaf_children: 0, parent: null};

for (var i = 1; i < tree.length; i++) {
    parent_index = parseInt(readline()) - 1;
    tree[i] = { isLeaf: true, leaf_children: 0, parent: parent_index};
    tree[parent_index]["isLeaf"] = false;
    tree[parent_index]["leaf_children"] += 1;
}

print(isElka(tree));

var nodesAmount = readline();
var nodes = new Array(parseInt(nodesAmount) - 1);
var tree = new Array(parseInt(nodesAmount));

for (var i = 0; i < nodes.length; i++) {
    nodes[i] = readline() - 1;
}

for (var i = 0; i < tree.length; i++) {
    tree[i] = [];
}

nodes.forEach(function(node, i) {
    tree[node].push(i + 1);
});
var result = 'Yes';
testLevel(tree[0]);
print(result);

function testLevel(nodes) {
    var leaves = 0;
    nodes.forEach(function(node) {
        if (!tree[node][0]) leaves++;
    });
    if (leaves < 3) {
        result = 'No';
    } else {
        nodes.forEach(function(node) {
            if (tree[node][0]) {
                return testLevel(tree[node]);
            }
        });
    }
}

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}

// utils
const MOD = 1e9 + 7;
const mod = (n) => ((n % MOD) + MOD) % MOD;
const add = (a, b) => mod(mod(a) + mod(b));
const sub = (a, b) => mod(mod(a) - mod(b));
function mul() {
  for (var a = arguments, r = a[0], i = a.length; --i; )
    r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;
  return r;
}
function inv(b) {
  for (var a = MOD, u = 0, v = 1, t; b; v = t)
    (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);
  u %= MOD;
  return u < 0 ? u + MOD : u;
}
function pow(base, n) {
  if (n === 0) return 1;
  let p = pow(base, Math.floor(n / 2));
  let res = mul(mod(p), mod(p));
  if (n % 2 === 1) res = mul(mod(res), base);
  return res;
}
function highestOneBit(i) {
  i |= i >> 1;
  i |= i >> 2;
  i |= i >> 4;
  i |= i >> 8;
  i |= i >> 16;
  return i - (i >>> 1);
}
function permutation(arr, len, store = "", permutations = []) {
  if (store.length === len) {
    permutations.push(store);
    return;
  }
  for (let i = 0; i < arr.length; i++) {
    const newArr = [...arr];
    const newChar = newArr.splice(i, 1);
    permutation(newArr, len, store.concat(newChar), permutations);
  }
  return permutations;
}

function main() {
  let len = +readLine();
  len = len - 1;
  let index = 2;
  const data = new Map();
  while (len--) {
    const n = +readLine();
    data.set(n, (data.get(n) || new Set()).add(index));
    index++;
  }

  for (let [key1, value1] of data) {
    for (let [key, value] of data) {
      if (value.has(key1)) value.delete(key1);
    }
  }

  for (let [key, value] of data) {
    if (value.size < 3) {
      console.log(`No`);
      return;
    }
  }
  console.log(`Yes`);
}

'use strict';
var tree = new Array(parseInt(readline()));
tree[0] = { isLeaf: true,
            leafs: 0,
            parent: null};

for (var i = 1; i < tree.length; i++) {
    var parentIndex = parseInt(readline()) - 1;
    tree[i] = { isLeaf: true,
                leafs: 0,
                parent: parentIndex};
    tree[parentIndex]["isLeaf"] = false;
    tree[parentIndex]["leafs"] += 1;
}

function isChristmasTree(tree) {
    for (var i = 0; i < tree.length; i++) {
    var leafs = 0;
        for (var j = 1 + i; j < tree.length; j++) {
            if (tree[j]["parent"] === i && tree[j]["isLeaf"])
                leafs += 1;
        }
        if (leafs < 3 && !tree[i].isLeaf)
            return "No";
    }
    return "Yes";
}

print(isChristmasTree(tree));

function isLeaf(node) {
    return Object.keys(node.children).length === 0;
}

// input
var n = parseInt(readline());

var nodes = new Array(n);
nodes[0] = {
    isLeaf: true,
    leaves: 0,
    parent: null
};

for (var i = 1; i < n; i++) {
    var parentIndex = parseInt(readline()) - 1;
    if (!nodes[i]) {
        // init current node
        nodes[i] = {
            isLeaf: true,
            leaves: 0,
            parent: parentIndex
        };
    }

    var currentNode = nodes[i];

    if (!nodes[parentIndex]) {
        // init parent node
        nodes[parentIndex] = {
            isLeaf: false,
            leaves: currentNode.isLeaf ? 1 : 0,
            parent: null
        };
    } else {
        // update parent node
        var parentNode = nodes[parentIndex];
        if (parentNode.isLeaf) {
            parentNode.isLeaf = false;
            var parentParentNode = nodes[parentNode.parent];
            if (parentParentNode) {
                parentParentNode.leaves = Math.max(0, parentParentNode.leaves - 1);
            }
        }

        if (currentNode.isLeaf) {
            parentNode.leaves++;
        }
    }
}

function isSpruce(tree) {
    for (var i = 0; i < n; i++) {
        var node = tree[i];
        if (!node.isLeaf && node.leaves < 3) {
            return 'No';
        }
    }
    return 'Yes';
}

print(isSpruce(nodes));

var n = parseInt(readline());;
//+prompt("Enter kol verwun");
var koli4estvoVerwun = new Array(n);

var roditelInex = 0;
var dannajaVetka;
var roditelVetka;
var mainVerwuna;
var verwuna;

function esListom(verwuna) {
    return Object.keys(verwuna.children).length === 0;
}
koli4estvoVerwun[0] = {
                      roditel: null,
                      listkov: 0,
                      esListom: true
                      }

    function findRes(data) {
for (var i = 0; i < n; i++) {
verwuna = data[i];
if (!verwuna.esListom && verwuna.listkov < 3) {
return 'No';
}
}
return 'Yes';
}

for (var i = 1; i < n; i++) {
    roditelInex = parseInt(readline()) - 1;
    //+prompt("data") - 1;
    if (!koli4estvoVerwun[i]) {
        koli4estvoVerwun[i] = {
                              roditel: roditelInex,
                              listkov: 0,
                              esListom: true
                              };
    }

dannajaVetka = koli4estvoVerwun[i];

if (!koli4estvoVerwun[roditelInex]) {
    koli4estvoVerwun[roditelInex] = {
        roditel: null,
        listkov: dannajaVetka.esListom ? 1 : 0,
        esListom: false
    };
} else {

roditelVetka = koli4estvoVerwun[roditelInex];
if (roditelVetka.esListom) {
    roditelVetka.esListom = false;

    mainVerwuna = koli4estvoVerwun[roditelVetka.roditel];
    if (mainVerwuna) {
        mainVerwuna.listkov = Math.max(0 , mainVerwuna.listkov -1);
    }
}
if (dannajaVetka.esListom) {
    roditelVetka.listkov++;
}
}
}
print(findRes(koli4estvoVerwun));
//alert(findRes(koli4estvoVerwun));

var n = parseInt(readline());;
//+prompt("Enter kol verwun");
var koli4estvoVerwun = [n];

var roditelInex = 0;
var dannajaVetka;
var roditelVetka;
var mainVerwuna;
var verwuna;

//function esListom(verwuna) {
  //  return Object.keys(verwuna.children).length === 0;
//}
koli4estvoVerwun[0] = {
                      roditel: null,
                      listkov: 0,
                      esListom: true
                      }

    function findRes(data) {
for (var i = 0; i < n; i++) {
verwuna = data[i];
if (!verwuna.esListom && verwuna.listkov < 3) {
return 'No';
}
}
return 'Yes';
}

for (var i = 1; i < n; i++) {
    roditelInex = parseInt(readline()) - 1;
    //+prompt("data") - 1;
    if (!koli4estvoVerwun[i]) {
        koli4estvoVerwun[i] = {
                              roditel: roditelInex,
                              listkov: 0,
                              esListom: true
                              };
    }

dannajaVetka = koli4estvoVerwun[i];

if (!koli4estvoVerwun[roditelInex]) {
    koli4estvoVerwun[roditelInex] = {
        roditel: null,
        listkov: dannajaVetka.esListom ? 1 : 0,
        esListom: false
    };
} else {

roditelVetka = koli4estvoVerwun[roditelInex];
if (roditelVetka.esListom) {
    roditelVetka.esListom = false;

    mainVerwuna = koli4estvoVerwun[roditelVetka.roditel];
    if (mainVerwuna) {
        mainVerwuna.listkov = Math.max(0 , mainVerwuna.listkov -1);
    }
}
if (dannajaVetka.esListom) {
    roditelVetka.listkov++;
}
}
}
print(findRes(koli4estvoVerwun));
//alert(findRes(koli4estvoVerwun));

var n = parseInt(readline());;
//+prompt("Enter kol verwun");
var koli4estvoVerwun = new Array(n);

var roditelInex = 0;
var dannajaVetka;
var roditelVetka;
var mainVerwuna;
var verwuna;

function esListom(verwuna) {
    return Object.keys(verwuna.children).length === 0;
}
koli4estvoVerwun[0] = {
                      roditel: null,
                      listkov: 0,
                      esListom: true
                      }

for (var i = 1; i < n; i++) {
    roditelInex = parseInt(readline()) - 1;
    //+prompt("data") - 1;
    if (!koli4estvoVerwun[i]) {
        koli4estvoVerwun[i] = {
                              roditel: roditelInex,
                              listkov: 0,
                              esListom: true
                              };
    }

dannajaVetka = koli4estvoVerwun[i];

if (!koli4estvoVerwun[roditelInex]) {
    koli4estvoVerwun[roditelInex] = {
        roditel: null,
        listkov: dannajaVetka.esListom ? 1 : 0,
        esListom: false
    };
} else {

roditelVetka = koli4estvoVerwun[roditelInex];
if (roditelVetka.esListom) {
    roditelVetka.esListom = false;

    mainVerwuna = koli4estvoVerwun[roditelVetka.roditel];
    if (mainVerwuna) {
        mainVerwuna.listkov = Math.max(0 , mainVerwuna.listkov -1);
    }
}
if (dannajaVetka.esListom) {
    roditelVetka.listkov++;
}
}
}
function findRes(data) {
    for (var i = 0; i < n; i++) {
       verwuna = data[i];
       if (!verwuna.esListom && verwuna.listkov < 3) {
           return 'No';
       }
    }
    return 'Yes';
}

print(findRes(koli4estvoVerwun));
//alert(findRes(koli4estvoVerwun));

var n = parseInt(readline());;
//+prompt("Enter kol verwun");
var koli4estvoVerwun = [n];

var roditelInex = 0;
var dannajaVetka;
var roditelVetka;
var mainVerwuna;
var verwuna;

koli4estvoVerwun[0] = {
                      roditel: null,
                      listkov: 0,
                      esListom: true
                      }

    function findRes(data) {
for (var i = 0; i < n; i++) {
verwuna = data[i];
if (!verwuna.esListom && verwuna.listkov < 3) {
return 'No';
}
}
return 'Yes';
}

for (var i = 1; i < n; i++) {
    roditelInex = parseInt(readline()) - 1;
    //+prompt("data") - 1;
    if (!koli4estvoVerwun[i]) {
        koli4estvoVerwun[i] = {
                              roditel: roditelInex,
                              listkov: 0,
                              esListom: true
                              };
    }

dannajaVetka = koli4estvoVerwun[i];

if (!koli4estvoVerwun[roditelInex]) {
    koli4estvoVerwun[roditelInex] = {
        roditel: null,
        listkov: dannajaVetka.esListom ? 1 : 0,
        esListom: false
    };
} else {

roditelVetka = koli4estvoVerwun[roditelInex];
if (roditelVetka.esListom) {
    roditelVetka.esListom = false;

    mainVerwuna = koli4estvoVerwun[roditelVetka.roditel];
    if (mainVerwuna) {
        mainVerwuna.listkov = Math.max(0 , mainVerwuna.listkov -1);
    }
}
if (dannajaVetka.esListom) {
    roditelVetka.listkov++;
}
}
}
print(findRes(koli4estvoVerwun));
//alert(findRes(koli4estvoVerwun));

var n = parseInt(readline());;
//+prompt("Enter kol verwun");
var koli4estvoVerwun = [n];

var roditelInex = 0;
var dannajaVetka;
var roditelVetka;
var mainVerwuna;
var verwuna;

function esListom(verwuna) {
    return Object.keys(verwuna.children).length === 0;
}
koli4estvoVerwun[0] = {
                      roditel: null,
                      listkov: 0,
                      esListom: true
                      }

    function findRes(data) {
for (var i = 0; i < n; i++) {
verwuna = data[i];
if (!verwuna.esListom && verwuna.listkov < 3) {
return 'No';
}
}
return 'Yes';
}

for (var i = 1; i < n; i++) {
    roditelInex = parseInt(readline()) - 1;
    //+prompt("data") - 1;
    if (!koli4estvoVerwun[i]) {
        koli4estvoVerwun[i] = {
                              roditel: roditelInex,
                              listkov: 0,
                              esListom: true
                              };
    }

dannajaVetka = koli4estvoVerwun[i];

if (!koli4estvoVerwun[roditelInex]) {
    koli4estvoVerwun[roditelInex] = {
        roditel: null,
        listkov: dannajaVetka.esListom ? 1 : 0,
        esListom: false
    };
} else {

roditelVetka = koli4estvoVerwun[roditelInex];
if (roditelVetka.esListom) {
    roditelVetka.esListom = false;

    mainVerwuna = koli4estvoVerwun[roditelVetka.roditel];
    if (mainVerwuna) {
        mainVerwuna.listkov = Math.max(0 , mainVerwuna.listkov -1);
    }
}
if (dannajaVetka.esListom) {
    roditelVetka.listkov++;
}
}
}
print(findRes(koli4estvoVerwun));
//alert(findRes(koli4estvoVerwun));

 'use strict';
var tree = new Array(parseInt(readline()));
tree[0] = { isLeaf: true,
            leafChildren: 0,
            leafParent: null};
var parentIndex = 0;
for (var i = 1; i < tree.length; i++) {
    parentIndex = parseInt(readline()) - 1;
    tree[i] = { isLeaf: true,
                leafChildren: 0,
                parent: parentIndex};
    tree[parentIndex]["isLeaf"] = false;
    tree[parentIndex]["leafChildren"] += 1;
}

function isNewYearTree(tree) {
    var leafChildren = 0;
    for (var i = 0; i < tree.length; i++) {
        for (var j = i+1; j < tree.length; j++)
            if (tree[j]["parent"] === i && tree[j]["isLeaf"])
                    leafChildren += 1;
            if (leafChildren < 3 && !tree[i].isLeaf)
                    return "No";
    }
    return "Yes";
}

print(isNewYearTree(tree));

'use strict';
var tree = new Array(parseInt(readline()));
tree[0] = { isLeaf: true,
            leafChildren: 0,
            parent: null};
var parentIndex = 0;
for (var i = 1; i < tree.length; i++) {
    parentIndex = parseInt(readline()) - 1;
    tree[i] = { isLeaf: true,
                leafChildren: 0,
                parent: parentIndex};
    tree[parentIndex]["isLeaf"] = false;
    tree[parentIndex]["leafChildren"] += 1;
}

function isNewYearTree(tree) {
    var leafChildren = 0;
    for (var i = 0; i < tree.length; i++) {
        for (var j = i+1; j < tree.length; j++)
            if (tree[j]["isLeaf"] && tree[j]["parent"] === i) {
                    leafChildren += 1;
            }
            if (!tree[i].isLeaf && leafChildren < 3) return "No";
    }
    return "Yes";
}

print(isNewYearTree(tree));

var number = parseInt(readline());
var tree = new Array(number);

tree[0] = { isLeaf: true, children: 0, parent: null};

for (var i = 1; i < number; i++) {
    parent_index = parseInt(readline()) - 1;
    tree[i] = { isLeaf: true, children: 0, parent: parent_index};
    tree[parent_index]["children"] += 1;
    tree[parent_index]["isLeaf"] = false;
}

var res = "Yes";
for (var i = 0; i < tree.length; i++) {
    if (!tree[i].isLeaf && tree[i]["children"] < 3){
        res = "No";
    }
}

print(res);

var number = parseInt(readline());
var tree = new Array(number);

function reduceLeafChildNumber(tree, parent_index) {
    if (tree[parent_index]["parent"] !== null) {
        tree[tree[parent_index]["parent"]]["leaf_children"] -= 1;
        return reduceLeafChildNumber(tree, tree[parent_index]["parent"]);
    } else {
        return tree;
    }
}
tree[0] = { isLeaf: true, leaf_children: 0, parent: null};

for (var i = 1; i < number; i++) {
    parent_index = parseInt(readline()) - 1;
    tree[i] = { isLeaf: true, children: 0, parent: parent_index};
    tree[parent_index]["leaf_children"] += 1;
    tree[parent_index]["isLeaf"] = false;

    tree = reduceLeafChildNumber(tree, parent_index);
}

var res = "Yes";
for (var i = 0; i < tree.length; i++) {
    if (!tree[i].isLeaf && tree[i]["leaf_children"] < 3){
        res = "No";
    }
}

print(res);

function reduceLeafChildNumber(tree, parent_index) {
    if (tree[parent_index]["parent"] !== null) {
        tree[tree[parent_index]["parent"]]["leaf_children"] -= 1;
        return reduceLeafChildNumber(tree, tree[parent_index]["parent"]);
    }
    return tree;
}

var res = "Yes";
var tree = new Array(parseInt(readline()));
tree[0] = { isLeaf: true, leaf_children: 0, parent: null};

for (var i = 1; i < tree.length; i++) {
    parent_index = parseInt(readline()) - 1;
    tree[i] = { isLeaf: true, leaf_children: 0, parent: parent_index};
    tree[parent_index]["isLeaf"] = false;

    if (tree[parent_index]["leaf_children"] === 0) tree = reduceLeafChildNumber(tree, parent_index);
    tree[parent_index]["leaf_children"] += 1;
}

for (var i = 0; i < tree.length; i++)
    if (!tree[i].isLeaf && tree[i]["leaf_children"] < 3) res = "No";

print(res);

function reduceLeafChildNumber(tree, parent_index) {
    if (tree[parent_index]["parent"] !== null) {
        tree[tree[parent_index]["parent"]]["leaf_children"] -= 1;
        return reduceLeafChildNumber(tree, tree[parent_index]["parent"]);
    }
    return tree;
}

var res = "Yes";
var tree = new Array(parseInt(readline()));
tree[0] = { isLeaf: true, leaf_children: 0, parent: null};

for (var i = 1; i < tree.length; i++) {
    parent_index = parseInt(readline()) - 1;
    tree[i] = { isLeaf: true, leaf_children: 0, parent: parent_index};
    tree[parent_index]["leaf_children"] += 1;
    tree[parent_index]["isLeaf"] = false;

    tree = reduceLeafChildNumber(tree, parent_index);
}

for (var i = 0; i < tree.length; i++) {
    if (!tree[i].isLeaf && tree[i]["leaf_children"] < 3){
        res = "No";
    }
}

print(res);

var nodesAmount = readline();
var nodes = new Array(parseInt(nodesAmount) - 1);
var tree = new Array(parseInt(nodesAmount));

for (var i = 0; i < nodes.length; i++) {
    nodes[i] = readline() - 1;
}

for (var i = 0; i < tree.length; i++) {
    tree[i] = [];
}

nodes.forEach(function(node, i) {
    tree[node].push(i + 1);
});

print(testLevel(tree[0]));

function testLevel(nodes) {

    if (!nodes[0]) {
        return true;
    }

    var leaves = 0;

    nodes.forEach(function(node) {
        if (!tree[node][0]) {
            leaves++;
        }
    });

    if (leaves < 3) {
        return 'No';
    }

    nodes.forEach(function(node) {
        testLevel(tree[node]);
    });

    return 'Yes'
}

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}

// utils
const MOD = 1e9 + 7;
const mod = (n) => ((n % MOD) + MOD) % MOD;
const add = (a, b) => mod(mod(a) + mod(b));
const sub = (a, b) => mod(mod(a) - mod(b));
function mul() {
  for (var a = arguments, r = a[0], i = a.length; --i; )
    r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;
  return r;
}
function inv(b) {
  for (var a = MOD, u = 0, v = 1, t; b; v = t)
    (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);
  u %= MOD;
  return u < 0 ? u + MOD : u;
}
function pow(base, n) {
  if (n === 0) return 1;
  let p = pow(base, Math.floor(n / 2));
  let res = mul(mod(p), mod(p));
  if (n % 2 === 1) res = mul(mod(res), base);
  return res;
}
function highestOneBit(i) {
  i |= i >> 1;
  i |= i >> 2;
  i |= i >> 4;
  i |= i >> 8;
  i |= i >> 16;
  return i - (i >>> 1);
}
function permutation(arr, len, store = "", permutations = []) {
  if (store.length === len) {
    permutations.push(store);
    return;
  }
  for (let i = 0; i < arr.length; i++) {
    const newArr = [...arr];
    const newChar = newArr.splice(i, 1);
    permutation(newArr, len, store.concat(newChar), permutations);
  }
  return permutations;
}

function main() {
  let len = +readLine();
  len = len - 1;
  const data = [];
  while (len--) {
    const n = +readLine();
    data.push(n);
  }
  data.sort((a, b) => a - b);
  let [prev, prevCount] = [null, 0];

  for (let i = 0; i < data.length; i++) {
    const current = data[i];
    if (prev === current) {
      prevCount++;
    } else {
      if (prev !== null) {
        prevCount = prevCount - 1;
        if (prevCount < 3) {
          console.log(`No`);
          return;
        }
      }
      prev = current;
      prevCount = 1;
    }
  }
  console.log(`Yes`);
}


"use strict";

function cmp (a, b) {
    if (a < b)
        return -1;
    if (a === b)
        return 0;
    return 1;
}

function solve(n, k, ts) {
    var negative = [];
    for (var i = 0; i < ts.length; i++)
        if (ts[i] < 0)
            negative.push(i);
    if (negative.length > k)
        return -1;
    if (negative.length === 0)
        return 0;
    k -= negative.length;
    var diffs = [];
    for (i = 1; i < negative.length; i++)
        if (negative[i] !== negative[i - 1] + 1)
            diffs.push(negative[i] - negative[i - 1] - 1);
    diffs.sort(cmp);
    i = 0;
    var segms = diffs.length + 1;
    while (i < diffs.length && diffs[i] <= k) {
        k -= diffs[i];
        i++;
        segms--;
    }
    var res = 2 * segms;
    if (k >= n - negative[negative.length - 1] - 1)
        res--;
    return res;
}

var line = readline().split(' ');
var n = parseInt(line[0]);
var k = parseInt(line[1]);
var ts = readline().split(' ').map(function(s) { return parseInt(s); });
print(solve(n, k, ts));

// Generated by CoffeeScript 1.10.0

/*
lines = '''
4 8
0 0 -1 0 0 -1 -1 -1 0 0 -1 0 -1 0 -1 -1 -1 0 0 0 -1
'''.split '\n'

readline = -> lines.shift()
print = console.log
 */

(function() {
  var currentRange, currentTire, finalGap, gap, gaps, gapsConsumed, i, j, k, l, len, len1, len2, m, n, range, ref, t, temp, totalChanges, totalUsedTime, winterRanges;

  ref = readline().split(' ').map(Number), n = ref[0], k = ref[1];

  temp = readline().split(' ').map(Number);

  winterRanges = [];

  currentTire = 'summer';

  currentRange = [];

  for (i = j = 0, len = temp.length; j < len; i = ++j) {
    t = temp[i];
    if (t < 0 && currentTire === 'summer') {
      currentRange.push(i);
      currentTire = 'winter';
    } else if (t >= 0 && currentTire === 'winter') {
      currentRange.push(i);
      winterRanges.push(currentRange);
      currentRange = [];
      currentTire = 'summer';
    }
  }

  if (currentTire === 'winter') {
    currentRange.push(temp.length);
    winterRanges.push(currentRange);
  }

  totalChanges = winterRanges.length * 2;

  if (winterRanges.length === 0) {
    print('0');
  } else {
    totalUsedTime = winterRanges.map(function(x) {
      return x[1] - x[0];
    }).reduce(function(a, b) {
      return a + b;
    });
    if (totalUsedTime > k) {
      print('-1');
    } else {
      gaps = [];
      for (i = l = 0, len1 = winterRanges.length; l < len1; i = ++l) {
        range = winterRanges[i];
        if (i > 0) {
          gaps.push(range[0] - winterRanges[i - 1][1]);
        }
      }
      gaps.sort(function(a, b) {
        return a - b;
      });
      gapsConsumed = 0;
      for (m = 0, len2 = gaps.length; m < len2; m++) {
        gap = gaps[m];
        totalUsedTime += gap;
        if (totalUsedTime <= k) {
          gapsConsumed += 1;
          totalChanges -= 2;
        } else {
          totalUsedTime -= gap;
          break;
        }
      }
      finalGap = temp.length - winterRanges[winterRanges.length - 1][1];
      if (totalUsedTime + finalGap <= k) {
        totalChanges -= 1;
      }
      print(totalChanges);
    }
  }

}).call(this);

// Generated by CoffeeScript 1.10.0

/*
lines = '''
4 3
-5 20 -3 0
'''.split '\n'

readline = -> lines.shift()
print = console.log
 */

(function() {
  var currentRange, currentTire, finalGap, gap, gaps, i, j, k, l, len, len1, len2, m, n, range, ref, t, temp, totalChanges, totalUsedTime, winterRanges;

  ref = readline().split(' ').map(Number), n = ref[0], k = ref[1];

  temp = readline().split(' ').map(Number);

  winterRanges = [];

  currentTire = 'summer';

  currentRange = [];

  for (i = j = 0, len = temp.length; j < len; i = ++j) {
    t = temp[i];
    if (t < 0 && currentTire === 'summer') {
      currentRange.push(i);
      currentTire = 'winter';
    } else if (t >= 0 && currentTire === 'winter') {
      currentRange.push(i);
      winterRanges.push(currentRange);
      currentRange = [];
      currentTire = 'summer';
    }
  }

  if (currentRange.length > 0) {
    currentRange.push(temp.length);
    winterRanges.push(currentRange);
  }

  totalChanges = winterRanges.length * 2;

  totalUsedTime = winterRanges.map(function(x) {
    return x[1] - x[0];
  }).reduce(function(a, b) {
    return a + b;
  });

  if (totalUsedTime > k) {
    print('-1');
  } else {
    gaps = [];
    for (i = l = 0, len1 = winterRanges.length; l < len1; i = ++l) {
      range = winterRanges[i];
      if (i > 0) {
        gaps.push(range[0] - winterRanges[i - 1][1]);
      }
    }
    gaps.sort();
    for (m = 0, len2 = gaps.length; m < len2; m++) {
      gap = gaps[m];
      totalUsedTime += gap;
      if (totalUsedTime <= k) {
        totalChanges -= 2;
      } else {
        totalUsedTime -= gap;
        break;
      }
    }
    finalGap = temp.length - winterRanges[winterRanges.length - 1][1];
    if (totalUsedTime + finalGap <= k) {
      totalChanges -= 1;
    }
    print(totalChanges);
  }

}).call(this);

// Generated by CoffeeScript 1.10.0

/*
lines = '''
4 8
0 0 -1 0 0 -1 -1 -1 0 0
'''.split '\n'

readline = -> lines.shift()
print = console.log
 */

(function() {
  var currentRange, currentTire, finalGap, gap, gaps, i, j, k, l, len, len1, len2, m, n, range, ref, t, temp, totalChanges, totalUsedTime, winterRanges;

  ref = readline().split(' ').map(Number), n = ref[0], k = ref[1];

  temp = readline().split(' ').map(Number);

  winterRanges = [];

  currentTire = 'summer';

  currentRange = [];

  for (i = j = 0, len = temp.length; j < len; i = ++j) {
    t = temp[i];
    if (t < 0 && currentTire === 'summer') {
      currentRange.push(i);
      currentTire = 'winter';
    } else if (t >= 0 && currentTire === 'winter') {
      currentRange.push(i);
      winterRanges.push(currentRange);
      currentRange = [];
      currentTire = 'summer';
    }
  }

  if (currentRange.length > 0) {
    currentRange.push(temp.length);
    winterRanges.push(currentRange);
  }

  totalChanges = winterRanges.length * 2;

  totalUsedTime = winterRanges.map(function(x) {
    return x[1] - x[0];
  }).reduce(function(a, b) {
    return a + b;
  });

  if (totalUsedTime > k) {
    print('-1');
  } else {
    gaps = [];
    for (i = l = 0, len1 = winterRanges.length; l < len1; i = ++l) {
      range = winterRanges[i];
      if (i > 0) {
        gaps.push(range[0] - winterRanges[i - 1][1]);
      }
    }
    gaps.sort();
    for (m = 0, len2 = gaps.length; m < len2; m++) {
      gap = gaps[m];
      totalUsedTime += gap;
      if (totalUsedTime <= k) {
        totalChanges -= 2;
      } else {
        totalUsedTime -= gap;
        break;
      }
    }
    finalGap = temp.length - winterRanges[winterRanges.length - 1][1];
    if (totalUsedTime + finalGap <= k) {
      totalChanges -= 1;
    }
    if (totalChanges > 12000) {
      print('WINTER RANGES:', winterRanges.length);
      print('TOTAL USED TIME:', totalUsedTime);
      print('SOME GAPS:', gaps.slice(0, 10));
      print('FINAL GAP', finalGap);
    }
    print(totalChanges);
  }

}).call(this);

// Generated by CoffeeScript 1.10.0

/*
lines = '''
4 8
0 0 -1 0 0 -1 -1 -1 0 0 -1 0 -1 0 -1 -1 -1 0 0 0 -1
'''.split '\n'

readline = -> lines.shift()
print = console.log
 */

(function() {
  var currentRange, currentTire, finalGap, gap, gaps, gapsConsumed, i, j, k, l, len, len1, len2, m, n, range, ref, t, temp, totalChanges, totalUsedTime, winterRanges;

  ref = readline().split(' ').map(Number), n = ref[0], k = ref[1];

  temp = readline().split(' ').map(Number);

  winterRanges = [];

  currentTire = 'summer';

  currentRange = [];

  for (i = j = 0, len = temp.length; j < len; i = ++j) {
    t = temp[i];
    if (t < 0 && currentTire === 'summer') {
      currentRange.push(i);
      currentTire = 'winter';
    } else if (t >= 0 && currentTire === 'winter') {
      currentRange.push(i);
      winterRanges.push(currentRange);
      currentRange = [];
      currentTire = 'summer';
    }
  }

  if (currentTire === 'winter') {
    currentRange.push(temp.length);
    winterRanges.push(currentRange);
  }

  totalChanges = winterRanges.length * 2;

  totalUsedTime = winterRanges.map(function(x) {
    return x[1] - x[0];
  }).reduce(function(a, b) {
    return a + b;
  });

  if (totalUsedTime > k) {
    print('-1');
  } else {
    gaps = [];
    for (i = l = 0, len1 = winterRanges.length; l < len1; i = ++l) {
      range = winterRanges[i];
      if (i > 0) {
        gaps.push(range[0] - winterRanges[i - 1][1]);
      }
    }
    gaps.sort();
    gapsConsumed = 0;
    for (m = 0, len2 = gaps.length; m < len2; m++) {
      gap = gaps[m];
      totalUsedTime += gap;
      if (totalUsedTime <= k) {
        gapsConsumed += 1;
        totalChanges -= 2;
      } else {
        totalUsedTime -= gap;
        break;
      }
    }
    finalGap = temp.length - winterRanges[winterRanges.length - 1][1];
    if (totalUsedTime + finalGap <= k) {
      totalChanges -= 1;
    }
    if (totalChanges > 12000) {
      print('WINTER RANGES:', winterRanges.length);
      print('TOTAL USED TIME:', totalUsedTime);
      print('TOTAL NUMBER OF GAPS', gaps.length);
      print('GAPS CONSUMED:', gapsConsumed);
      print('FINAL GAP', gaps[gapsConsumed - 1], gaps[gapsConsumed], gaps[gapsConsumed + 1]);
      print('NUMBER OF 1-GAPS', gaps.filter(function(x) {
        return x === 1;
      }).length);
      print('SOME GAPS:', gaps.slice(0, 10));
      print('FINAL GAP', finalGap);
    }
    print(totalChanges);
  }

}).call(this);

// Generated by CoffeeScript 1.10.0

/*
lines = '''
4 3
-5 20 -3 0
'''.split '\n'

readline = -> lines.shift()
print = console.log
 */

(function() {
  var currentRange, currentTire, finalGap, gap, gaps, i, j, k, l, len, len1, len2, m, n, range, ref, t, temp, totalChanges, totalUsedTime, winterRanges;

  ref = readline().split(' ').map(Number), n = ref[0], k = ref[1];

  temp = readline().split(' ').map(Number);

  winterRanges = [];

  currentTire = 'summer';

  currentRange = [];

  for (i = j = 0, len = temp.length; j < len; i = ++j) {
    t = temp[i];
    if (t < 0 && currentTire === 'summer') {
      currentRange.push(i);
      currentTire = 'winter';
    } else if (t >= 0 && currentTire === 'winter') {
      currentRange.push(i);
      winterRanges.push(currentRange);
      currentRange = [];
      currentTire = 'summer';
    }
  }

  if (currentRange.length > 0) {
    currentRange.push(temp.length);
    winterRanges.push(currentRange);
  }

  totalChanges = winterRanges.length * 2;

  totalUsedTime = winterRanges.map(function(x) {
    return x[1] - x[0];
  }).reduce(function(a, b) {
    return a + b;
  });

  gaps = [];

  for (i = l = 0, len1 = winterRanges.length; l < len1; i = ++l) {
    range = winterRanges[i];
    if (i > 0) {
      gaps.push(range[0] - winterRanges[i - 1][1]);
    }
  }

  gaps.sort();

  for (m = 0, len2 = gaps.length; m < len2; m++) {
    gap = gaps[m];
    totalUsedTime += gap;
    if (totalUsedTime <= k) {
      totalChanges -= 2;
    } else {
      totalUsedTime -= gap;
      break;
    }
  }

  finalGap = temp.length - winterRanges[winterRanges.length - 1][1];

  if (totalUsedTime + finalGap <= k) {
    totalChanges -= 1;
  }

  print(totalChanges);

}).call(this);

// Generated by CoffeeScript 1.10.0

/*
lines = '''
4 8
0 0 -1 0 0 -1 -1 -1 0 0
'''.split '\n'

readline = -> lines.shift()
print = console.log
 */

(function() {
  var currentRange, currentTire, finalGap, gap, gaps, gapsConsumed, i, j, k, l, len, len1, len2, m, n, range, ref, t, temp, totalChanges, totalUsedTime, winterRanges;

  ref = readline().split(' ').map(Number), n = ref[0], k = ref[1];

  temp = readline().split(' ').map(Number);

  winterRanges = [];

  currentTire = 'summer';

  currentRange = [];

  for (i = j = 0, len = temp.length; j < len; i = ++j) {
    t = temp[i];
    if (t < 0 && currentTire === 'summer') {
      currentRange.push(i);
      currentTire = 'winter';
    } else if (t >= 0 && currentTire === 'winter') {
      currentRange.push(i);
      winterRanges.push(currentRange);
      currentRange = [];
      currentTire = 'summer';
    }
  }

  if (currentRange.length > 0) {
    currentRange.push(temp.length);
    winterRanges.push(currentRange);
  }

  totalChanges = winterRanges.length * 2;

  totalUsedTime = winterRanges.map(function(x) {
    return x[1] - x[0];
  }).reduce(function(a, b) {
    return a + b;
  });

  if (totalUsedTime > k) {
    print('-1');
  } else {
    gaps = [];
    for (i = l = 0, len1 = winterRanges.length; l < len1; i = ++l) {
      range = winterRanges[i];
      if (i > 0) {
        gaps.push(range[0] - winterRanges[i - 1][1]);
      }
    }
    gaps.sort();
    gapsConsumed = 0;
    for (m = 0, len2 = gaps.length; m < len2; m++) {
      gap = gaps[m];
      totalUsedTime += gap;
      if (totalUsedTime <= k) {
        gapsConsumed += 1;
        totalChanges -= 2;
      } else {
        totalUsedTime -= gap;
        break;
      }
    }
    finalGap = temp.length - winterRanges[winterRanges.length - 1][1];
    if (totalUsedTime + finalGap <= k) {
      totalChanges -= 1;
    }
    if (totalChanges > 12000) {
      print('WINTER RANGES:', winterRanges.length);
      print('TOTAL USED TIME:', totalUsedTime);
      print('GAPS CONSUMED:', gapsConsumed);
      print('FINAL GAP', gaps[gapsConsumed - 1], gaps[gapsConsumed], gaps[gapsConsumed + 1]);
      print('SOME GAPS:', gaps.slice(0, 10));
      print('FINAL GAP', finalGap);
    }
    print(totalChanges);
  }

}).call(this);

// Generated by CoffeeScript 1.10.0
(function() {
  var currentRange, currentTire, finalGap, gap, gaps, i, j, k, l, len, len1, len2, lines, m, n, range, readline, ref, t, temp, totalChanges, totalUsedTime, winterRanges;

  lines = '4 8\n0 0 -1 0 0 -1 -1 -1 0 0'.split('\n');

  readline = function() {
    return lines.shift();
  };

  /*
  print = console.log
   */

  ref = readline().split(' ').map(Number), n = ref[0], k = ref[1];

  temp = readline().split(' ').map(Number);

  winterRanges = [];

  currentTire = 'summer';

  currentRange = [];

  for (i = j = 0, len = temp.length; j < len; i = ++j) {
    t = temp[i];
    if (t < 0 && currentTire === 'summer') {
      currentRange.push(i);
      currentTire = 'winter';
    } else if (t >= 0 && currentTire === 'winter') {
      currentRange.push(i);
      winterRanges.push(currentRange);
      currentRange = [];
      currentTire = 'summer';
    }
  }

  if (currentRange.length > 0) {
    currentRange.push(temp.length);
    winterRanges.push(currentRange);
  }

  totalChanges = winterRanges.length * 2;

  totalUsedTime = winterRanges.map(function(x) {
    return x[1] - x[0];
  }).reduce(function(a, b) {
    return a + b;
  });

  if (totalUsedTime > k) {
    print('-1');
  } else {
    gaps = [];
    for (i = l = 0, len1 = winterRanges.length; l < len1; i = ++l) {
      range = winterRanges[i];
      if (i > 0) {
        gaps.push(range[0] - winterRanges[i - 1][1]);
      }
    }
    gaps.sort();
    for (m = 0, len2 = gaps.length; m < len2; m++) {
      gap = gaps[m];
      totalUsedTime += gap;
      if (totalUsedTime <= k) {
        totalChanges -= 2;
      } else {
        totalUsedTime -= gap;
        break;
      }
    }
    finalGap = temp.length - winterRanges[winterRanges.length - 1][1];
    if (totalUsedTime + finalGap <= k) {
      totalChanges -= 1;
    }
    if (totalChanges > 12000) {
      print('WINTER RANGES:', winterRanges.length);
      print('TOTAL USED TIME:', totalUsedTime);
      print('SOME GAPS:', gaps.slice(0, 10));
      print('FINAL GAP', finalGap);
    }
    print(totalChanges);
  }

}).call(this);


if (undefined == readline) {
	var fs = require('fs')
	var lines = fs.readFileSync('/dev/stdin', 'utf8').split("\n").reverse();
	var readline = function() {
		return lines.pop()
	}
}

if (undefined == print) {
	var print = console.log
}

var ints = function() {
	return readline().split(' ').map(function(n) {
		return parseInt(n)
	})
}

var numbers = ints(),
	x = numbers[1],
	counter = 0,
	temp = 0

numbers = ints().reduce(function(result, n) {
	if (undefined == result[n])
		result[n] = 0
	result[n] ++
	return result
}, {})

for (var n in numbers) {
	if (x == 0) {
		temp = numbers[n]
		if (temp > 1) {
			counter += (temp * (temp - 1)) / 2
		}
	} else {
		temp = numbers[n ^ x]
		if (undefined != temp)
			counter += temp * numbers[n]
		numbers[n] = undefined
	}
}

print(counter)

function sa(f, s){
        var x = Number(f.split(" ")[1]);
        var data = s.split(" ").map(Number);
        var arr = [];
        for(var i=0;i<=100000;i++){
            arr[i] = 0;
        }
        var res = 0;
        for(var i=0;i<data.length;i++){
            var result = data[i] ^ x;
            if(result<=100000){
                    res += arr[result];

            }
            arr[data[i]]++;
        }
        return res;
    }
    var f = readline();
    var s = readline();
    print(sa(f, s));

var ints = function() {
	return readline().split(' ').map(function(n) {
		return parseInt(n)
	})
}

var numbers = ints(),
	x = numbers[1],
	counter = 0,
	temp = 0

numbers = ints().reduce(function(result, n) {
	if (undefined == result[n])
		result[n] = 0
	result[n] ++
	return result
}, {})

for (var n in numbers) {
	temp = numbers[n ^ x]
	if (undefined != temp)
		counter += temp * numbers[n]
}

print(counter)

if (undefined == readline) {
	var fs = require('fs')
	var lines = fs.readFileSync('/dev/stdin', 'utf8').split("\n").reverse();
	var readline = function() {
		return lines.pop()
	}
}

if (undefined == print) {
	var print = console.log
}

var ints = function() {
	return readline().split(' ').map(function(n) {
		return parseInt(n)
	})
}

var numbers = ints(),
	x = numbers[1],
	counter = 0,
	temp = 0

numbers = ints().reduce(function(result, n) {
	if (undefined == result[n])
		result[n] = 0
	result[n] ++
	return result
}, {})

for (var n in numbers) {
	temp = numbers[n ^ x]
	if (undefined != temp)
		counter += temp * numbers[n]
	numbers[n] = undefined
}

print(counter)

function sa(f, s){
        var x = Number(f.split(" ")[1]);
        var data = s.split(" ").map(Number);
        var arr = [];
        for(var i=0;i<=100000;i++){
            arr[i] = 0;
        }
        for(var i=0;i<data.length;i++){
            arr[data[i]]++;
        }
        var res = 0;
        for(var i=0;i<=100000;i++){
            var result = i ^ x;
            if(result<=100000){
                if(result == i){
                        res += arr[result];
                } else {
                res += arr[result] * arr[i];
                }
            }
        }
        return res/2;
    }
    var f = readline();
    var s = readline();
    print(sa(f, s));

function sa(f, s){
        var x = Number(f.split(" ")[1]);
        var data = s.split(" ").map(Number);
        var arr = [];
        for(var i=0;i<=100000;i++){
            arr[i] = 0;
        }
        for(var i=0;i<data.length;i++){
            arr[data[i]]++;
        }
        var res = 0;
        for(var i=0;i<=100000;i++){
            var result = i ^ x;
            if(result<=100000){
                 if(result == 0){
if(arr[result] == 1){
continue;
}

if(arr[result] == 2){
res += arr[result];
continue;
}
res += arr[result] * 2;
continue;
}
                res += arr[result] * arr[i];
            }
        }
        return res/2;
    }
    var f = readline();
    var s = readline();
    print(sa(f, s));

function sa(f, s){
        var x = Number(f.split(" ")[1]);
        var data = s.split(" ").map(Number);
        var arr = [];
        for(var i=0;i<=100000;i++){
            arr[i] = 0;
        }
        for(var i=0;i<data.length;i++){
            arr[data[i]]++;
        }
        var res = 0;
        for(var i=0;i<data.length;i++){
            var result = data[i] ^ x;
            if(result<=100000){
                if(data[i] == result){
                    res += arr[data[i]] -1
                } else {
                    res += arr[data[i]] * arr[result];
                }
            }
        }
        return res/2;
    }
    var f = readline();
    var s = readline();
    print(sa(f, s));


var n = +readline(), a = readline().split(" ").map(Number);
var written = false,
notes = {
	25: 0,
	50: 0,
	100: 0
};

a.forEach(function(note, i){
	notes[note]++;

	if(note == 50){
		notes[25]--;
		if(notes[25] < 0){
			if(!written){
				print("NO");
				written = true;
			}
		}
	}

	if(note == 100){
		if(notes[50] > 0){
			notes[50]--;
			notes[25]--;
			if(notes[25] < 0){
				if(!written){
					print("NO");
					written = true;
				}
			}
		}
		else{
			notes[25] -= 3;
			if(notes[25] < 0){
				if(!written){
					print("NO");
					written = true;
				}
			}
		}
	}
});

if(!written){
	print("YES");
}

var m = [0,0,0];
var n;
var buff = new Array();
function read() {
	return readline().split(' ').map(Number);
}
function main() {
	n=read();
	buff=read();
	for (var i=0; i<n; i++) {
		switch(buff[i]) {
			case 25:
				m[0]++;
				break;
			case 50:
				m[1]++;
				if (m[0]>0) m[0]--;
				else {
					print("NO");
					return;
				}
				break;
			case 100:
				m[2]++;
				if (m[1]>0 && m[0]>0) m[1]--,m[0]--;
				else if (m[0]>=3) m[0]-=3;
				else {
					print("NO");
					return;
				}
				break;
		}
	}
	print("YES");
}
main();

var N = parseInt(readline());
function f(){var arr = readline().split(" ");

var clerk25 = 0, clerk50 = 0;
for (var i = 0; i < N; i++)
{
    var cur = arr[i];
    if (cur == 25) clerk25++;
    else
    {
        if (cur == 50)
        {clerk50++;
            if (clerk25 > 0) clerk25--;
            else {print("NO");  return false;}
        }
        if (cur == 100)
        {
            if ((clerk25 > 0 && clerk50>0))
            {
                clerk25--; clerk50--;
            }
            else if (clerk25>2) clerk25-=3;
            else {print("NO"); return false;}
        }
    }
}
print("YES");

}

f();

;(function () {

	var l25 = 0,
		l50 = 0;

	var n = +readline();
	var s = readline().split(' ');

	for (var i = 0; i < n; i++)
		switch (s[i]) {
			case '25':
				l25++;
				break;

			case '50':
				if (l25) {
					l25--;
					l50++;
				} else {
					print('NO');
					return;
				}
				break;

			case '100':
				if (l50 && l25) {
					l25--;
					l50--;
				} else if (l25 > 2) {
					l25 -= 3;
				} else {
					print('NO');
					return;
				}
				break;
		}
	print('YES');

}).call(this)

function trim(s) {
	return s.replace(/^\s+|\s+$/gm, '');
}

function tokenize(s) {
	return trim(s).split(/\s+/);
}

function tokenizeIntegers(s) {
	var tokens = tokenize(s);
	for (var i = 0; i < tokens.length; i += 1) {
		tokens[i] = parseInt(tokens[i], 10);
	};
	return tokens;
}

function main() {
	var n = parseInt(readline()),
		bills = tokenizeIntegers(readline()),
		cash = { 25: 0, 50: 0, 100: 0 };
	for (var i = 0; i < n; ++i) {
		var bill = bills[i];
		if (bill == 25) {
			cash[25] += 1;
		} else if (bill == 50 && cash[25] != 0) {
			cash[50] += 1;
			cash[25] -= 1;
		} else if (bill == 100 && cash[25] != 0 && cash[50] != 0) {
			cash[100] += 1;
			cash[25] -= 1;
			cash[50] -= 1;
		} else if (bill == 100 && cash[25] >= 3) {
			cash[100] += 1;
			cash[25] -= 3;
		} else {
			print('NO');
			return;
		}
	}
	print('YES');
}

main();

const fs = require('fs')

const readStdin = () => {
  return new Promise((resolve, reject) => {
    fs.readFile(0, (err, data) => {
      if (err) {
        reject(err)
      } else {
        resolve(data.toString())
      }
    })
  })
}

async function main () {
  const str = await readStdin()
  const lines = str.split('\n')
  const n = parseInt(lines[0])
  const bills = lines[1].split(' ').map(token => parseInt(token))

  let _25 = 0
  let _50 = 0
  let could = true

  bills.forEach((bill) => {
    if (bill === 25) {
      _25++
    } else if (bill === 50) {
      _50++
      if (_25 === 0) {
        could = false
      } else {
        _25--
      }
    } else {
      if (_50 > 0) {
        _50--
        if (_25 === 0) {
          could = false
        } else {
          _25--
        }
      } else if (_25 >= 3) {
        _25 -= 3
      } else {
        could = false
      }
    }
  })

  if (could) {
    console.log('YES')
  } else {
    console.log('NO')
  }
}

main().then(() => {})

// 349A     Очередь в кино

/*
function main_1(){
    var n = parseInt(readline());
    var ans = 0;
    while (n--) {
        var nums = readline().split(' ').map(Number);
        ans += (nums[2] - nums[0] + 1) * (nums[3] - nums[1] + 1);
    }
    print(ans);
}

function main(){
    var line  = readline();
    //var line = prompt();
    var n = line.length;
    //alert(line);
    var m = 0;
    for(i=0;i<n;i+=2){
        for(j=i+1;j<n;j+=2){
            var ex = [line.slice(0, i), '(', line.slice(i,j) , ')' , line.slice(j)].join('');
            m = Math.max(m,eval(ex));
        }
    }
    print(m);
}
*/

var n = parseInt(readline());
//var input_line = readline().split(' ').map(Number);
//var n =  input_line[0];
//var m =  input_line[1];

var arr = readline().split(' ').map(Number);

var summa25 = 0;
var summa50 = 0;
var out = '';
var x;

top:
for (var i = 0; i < arr.length; i++) {

    switch (arr[i]) {
        case 25:
            summa25 += 25;
            break;
        case 50:
            if (summa25 >= 25) {
                summa25 -= 25;
                summa50 += 50;
                break;
            } else {
                out = 'NO';
                break top;
            };
        case 100:
            x = 75;
            if (summa50 >= 50) {
                summa50 -= 50;
                x = 25;
            }
            if (summa25 >= x) {
                summa25 -= x;
                break;
            } else {
                out = 'NO';
                break top;
            };
    }

};

if (out === '') out = 'YES';

print(out);

var arrLen = readline().split(' ').map(Number);
var Arr = readline().split(' ').map(Number);
var arrM = [0, 0, 0];
var counter = 0;
for (var i=0; i<arrLen; i++) {
    if (Arr[i] == 25) {
        arrM[0] += 1;
        counter += 1;
    }
    if (Arr[i] == 50) {
        arrM[1] += 1;
        arrM[0] -= 1;
        if (arrM[0] < 0) {
            break;
        }
        counter += 1;
    }
    if (Arr[i] == 100) {
        if (arrM[1] == 0) {
            arrM[2] += 1;
            arrM[0] -= 3;
        }
        else {
            arrM[2] += 1;
            arrM[1] -= 1;
            arrM[0] -= 1;
        }
        if (arrM[0] < 0 || arrM[1] < 0) {
            break;
        }
        counter += 1;
    }
}
if (counter == arrLen) {
print("YES");
}
else {
print("NO");
}

var N = parseInt(readline());
function f(){var arr = readline().split(" ");

var clerk25 = 0, clerk50 = 0;
for (var i = 0; i < N; i++)
{
    var cur = arr[i];
    if (cur == 25) clerk25++;
    else
    {
        if (cur == 50)
        {
            if (clerk25 > 0) clerk25--;
            else {print("NO");  return false;}
        }
        if (cur == 100)
        {
            if ((clerk25 > 0 && clerk50>0))
            {
                clerk25--; clerk50--;
            }
            else if (clerk25>2) clerk25-=3;
            else {print("NO"); return false;}
        }
    }
}
print("YES");

}

f();

var n =  readline();
var str = readline().split(" ");
var cass = 0;
var r = 1;
		for (var i = 0; i<+n; i++){
			if(+str[i]==25)
				cass+=25;
			else if (cass>0){
				cass -= (+str[i]-25);
				cass += +str[i];
				}
			else {r=0; break;}
		}
		r==1? print("YES"):print("NO");

var n =   readline();
var str =  readline().split(" ");
var cass = 0;
var r = 1;
		for (var i = 0; i<+n; i++){
			if(+str[i]==25)
				cass+=25;
			else if (cass-(+str[i]-25)>=0){
				cass += +str[i];
				cass -= +str[i]-25;}
			else {r=0; break;}
			if (cass<0) break;
		}
		r==1? print("YES"):print("NO");

var n =  readline();
var str =  readline().split(" ");
var r = 1;
var cass = 0;
		for (var i = 0; i<+n; i++){
				if (+str[i]==25){
					cass+=25;
				}
				else if(+str[i]>25)  cass = cass-(+str[i]-25);
				else if (cass<0) break;
		}
		r==1&&cass>=0? print("YES"):print("NO");

var n =   readline();
var str =  readline().split(" ");
var cass = 0;
var r = 1;
		for (var i = 0; i<+n; i++){
			if(+str[i]==25)
				cass+=25;
			else {
				cass += +str[i];
				cass -= +str[i]-25;}
			if (cass<0) break;
		}
		r==1? print("YES"):print("NO");

var n =   readline();
var str =  readline().split(" ");
var cass = 0;
var r = 1;
		for (var i = 0; i<+n; i++){
			if(+str[i]==25)
				cass+=25;
			else {
				cass -= +str[i]-25;
				if (cass<0) { r=0; break;}
				cass += +str[i];}

		}
		r==1? print("YES"):print("NO");

var n =  readline();
var str = readline().split(" ");
var cass = 0;
var r = 1;
		for (var i = 0; i<+n; i++){
			if(+str[i]==25)
				cass+=25;
			else if ((+str[i]-25)<=cass&&cass>0){
				cass -= (+str[i]-25);
				cass += +str[i];
				}
			else {r=0; break;}
		}
		r==1? print("YES"):print("NO");

var n = readline();
var str = readline().split(" ");
var r = 1;
var cass = 0;
	for (var i = 0; i<+n; i++){
		if (str[i]>25&cass>0)
		cass = cass-(+str[i]-25);
		else if (+str[i]==25) cass+=25;
		else {r=0; break;}

	}
	r==1? print("YES"):print("NO");

var n = readline();
var str =  readline().split(" ");
var cass = 0;
var r = 1;
		for (var i = 0; i<+n; i++){
			if(+str[i]==25)
				cass+=25;
			else if (+str[i]==50){
				cass -=25;
				if (cass<0) { r=0; break;}
				cass +=50;
				}
			else if (+str[i]==100){
				cass -=75;
			    if (cass<0) { r=0; break;}
			}
		//	if (cass<0) { r=0; break;}

		}
		r==1? print("YES"):print("NO");

var n =   readline();
var str = readline().split(" ");
var cass = 0;
var r = 1;
		for (var i = 0; i<+n; i++){
			if(+str[i]==25)
				cass+=25;
			else
				cass += cass-(+str[i]-25);
			if (cass<0) {r=0; break;}
		}
		r==1? print("YES"):print("NO");

var n =  readline();
var str =  readline().split(" ");
var r = 1;
var cass = 0;
		for (var i = 0; i<+n; i++){
				if (+str[i]==25){
					cass+=25;
				}
				else cass = cass-(+str[i]-25);

		}
		r==1&&cass>=0? print("YES"):print("NO");

var n =   readline();
var str = readline().split(" ");
var cass = 0;
var r = 1;
		for (var i = 0; i<+n; i++){
			if(+str[i]==25)
				cass+=25;
			else if ((+str[i]-25)<=cass){
			cass += cass-(+str[i]-25);
				}
			else {r=0; break;}
		}
		r==1? print("YES"):print("NO");

var n =   readline();
var str = readline().split(" ");
var cass = 0;
var r = 1;
		for (var i = 0; i<+n; i++){
			if(+str[i]==25)
				cass+=25;
			else if (cass-(+str[i]-25)>=0&&cass>0)
				cass += cass-(+str[i]-25);
			else {r=0; break;}
		}
		r==1? print("YES"):print("NO");

var n =  readline();
var str = readline().split(" ");
var cass = 0;
var r = 1;
		for (var i = 0; i<+n; i++){
			if(+str[i]==25)
				cass+=25;
			else if ((+str[i]-25)<=cass){
				 var t = (+str[i]-25);
			     cass+= +str[i]-t;
				}
			else {r=0; break;}
		}
		r==1? print("YES"):print("NO");

var n =   readline();
var str = readline().split(" ");
var cass = 0;
var r = 1;
		for (var i = 0; i<+n; i++){
			if(+str[i]==25)
				cass+=25;
			else if (cass>0)
				cass += cass-(+str[i]-25);
			if (cass<0) {r=0; break;}
		}
		r==1? print("YES"):print("NO");

var n = readline();
var str =  readline().split(" ");
var cass = 0;
var r = 1;
		for (var i = 0; i<+n; i++){
			if(+str[i]==25)
				cass+=25;
			else if (+str[i]==50){
				cass -=25;
				if (cass<0) { r=0; break;}
				cass +=50;
				}
			else if (+str[i]==100){
				cass -=75;
			    if (cass<0) { r=0; break;}
				cass += 100;
			}
		//	if (cass<0) { r=0; break;}

		}
		r==1? print("YES"):print("NO");

var n =   readline();
var str =  readline().split(" ");
var cass = 0;
var r = 1;
		for (var i = 0; i<+n; i++){
			if(+str[i]==25)
				cass+=25;
			else {
				cass -= +str[i]-25;}
				if (cass<0) break;
				cass += +str[i];

		}
		r==1? print("YES"):print("NO");

var n =   readline();
var str = readline().split(" ");
var cass = 0;
var r = 1;
		for (var i = 0; i<+n; i++){
			if(+str[i]==25)
				cass+=25;
			else if (cass+Number(str[i])-(+str[i]-25)>0&&cass>0)
				cass = cass+Number(str[i])-(+str[i]-25);
			else {r=0; break;}
		}
		r==1? print("YES"):print("NO");

var n =   readline();
var str = readline().split(" ");
var cass = 0;
var r = 1;
		for (var i = 0; i<+n; i++){
			if(+str[i]==25)
				cass+=25;
			else if (cass-(+str[i]-25)>0&&cass>0)
				cass += cass-(+str[i]-25);
			else {r=0; break;}
		}
		r==1? print("YES"):print("NO");

var n =   readline();
var str =  readline().split(" ");
var cass = 0;
var r = 1;
		for (var i = 0; i<+n; i++){
			if(+str[i]==25)
				cass+=25;
			else {
				cass -= +str[i]-25;}
				if (cass<0) {break; r=0;}
				cass += +str[i];

		}
		r==1? print("YES"):print("NO");

// 349A     Очередь в кино

/*
function main_1(){
    var n = parseInt(readline());
    var ans = 0;
    while (n--) {
        var nums = readline().split(' ').map(Number);
        ans += (nums[2] - nums[0] + 1) * (nums[3] - nums[1] + 1);
    }
    print(ans);
}

function main(){
    var line  = readline();
    //var line = prompt();
    var n = line.length;
    //alert(line);
    var m = 0;
    for(i=0;i<n;i+=2){
        for(j=i+1;j<n;j+=2){
            var ex = [line.slice(0, i), '(', line.slice(i,j) , ')' , line.slice(j)].join('');
            m = Math.max(m,eval(ex));
        }
    }
    print(m);
}
*/

var n = parseInt(readline());
//var input_line = readline().split(' ').map(Number);
//var n =  input_line[0];
//var m =  input_line[1];

var arr = readline().split(' ').map(Number);

var summa25 = 0;
var summa50 = 0;
var out = '';
var x;

top:
for (var i = 0; i < arr.length; i++) {

    switch (arr[i]) {
        case 25:
            summa25 += 25;
            break;
        case 50:
            if (summa25 >= 25) {
                summa25 -= 25;
                summa50 += 50;
                break;
            } else {
                out = 'NO';
                break top;
            };
        case 100:
            x = 100;
            if (summa50 >= 50) {
                summa50 -= 50;
                x = 50;
            }
            if (summa25 >= x) {
                    summa25 -= x;
                    break;
            } else {
                out = 'NO';
                break top;
            };
    }

};

if (out === '') out = 'YES';

print(out);

// 349A     Очередь в кино

/*
function main_1(){
    var n = parseInt(readline());
    var ans = 0;
    while (n--) {
        var nums = readline().split(' ').map(Number);
        ans += (nums[2] - nums[0] + 1) * (nums[3] - nums[1] + 1);
    }
    print(ans);
}

function main(){
    var line  = readline();
    //var line = prompt();
    var n = line.length;
    //alert(line);
    var m = 0;
    for(i=0;i<n;i+=2){
        for(j=i+1;j<n;j+=2){
            var ex = [line.slice(0, i), '(', line.slice(i,j) , ')' , line.slice(j)].join('');
            m = Math.max(m,eval(ex));
        }
    }
    print(m);
}
*/

var n = parseInt(readline());
//var input_line = readline().split(' ').map(Number);
//var n =  input_line[0];
//var m =  input_line[1];

var arr = readline().split(' ').map(Number);

var summa25 = 0;
var summa50 = 0;
var summa100 = 0;
var out = '';

top:
for (var i = 0; i < arr.length; i++) {
    arr[i]
    switch (arr[i]) {
        case 25:
            summa25 += 25;
            break;
        case 50:
            if (summa25 > 25) {
                summa25 -= 25;
                summa50 += 50;
                break;
            } else {
                out = 'NO';
                break top;
            };
        case 100:
            if (summa50 > 50) {
                summa50 -= 50;
                summa100 += 100;
                break;
            } else {
                if (summa25 > 50) {
                    summa25 -= 50;
                    summa100 += 100;
                    break;
                } else {
                    out = 'NO';
                    break top;
                }
            };
    }

};

if (out === '') out = 'YES';

print(out);

// 349A     Очередь в кино

/*
function main_1(){
    var n = parseInt(readline());
    var ans = 0;
    while (n--) {
        var nums = readline().split(' ').map(Number);
        ans += (nums[2] - nums[0] + 1) * (nums[3] - nums[1] + 1);
    }
    print(ans);
}

function main(){
    var line  = readline();
    //var line = prompt();
    var n = line.length;
    //alert(line);
    var m = 0;
    for(i=0;i<n;i+=2){
        for(j=i+1;j<n;j+=2){
            var ex = [line.slice(0, i), '(', line.slice(i,j) , ')' , line.slice(j)].join('');
            m = Math.max(m,eval(ex));
        }
    }
    print(m);
}
*/

var n = parseInt(readline());
//var input_line = readline().split(' ').map(Number);
//var n =  input_line[0];
//var m =  input_line[1];

var arr = readline().split(' ').map(Number);

var summa25 = 0;
var summa50 = 0;
var summa100 = 0;
var out = '';

top:
for (var i = 0; i < arr.length; i++) {
    arr[i]
    switch (arr[i]) {
        case 25:
            summa25 += 25;
            break;
        case 50:
            if (summa25 >= 25) {
                summa25 -= 25;
                summa50 += 50;
                break;
            } else {
                out = 'NO';
                break top;
            };
        case 100:
            if (summa50 >= 50) {
                summa50 -= 50;
                summa100 += 100;
                break;
            } else {
                if (summa25 >= 50) {
                    summa25 -= 50;
                    summa100 += 100;
                    break;
                } else {
                    out = 'NO';
                    break top;
                }
            };
    }

};

if (out === '') out = 'YES';

print(out);

var arrLen = readline().split(' ').map(Number);
var Arr = readline().split(' ').map(Number);
var arrM = [0, 0, 0];
var counter = 0;
for (var i=0; i<arrLen; i++) {
    if (Arr[i] == 25) {
        arrM[0] += 1;
        counter += 1;
    }
    if (Arr[i] == 50) {
        arrM[1] += 1;
        arrM[0] -= 1;
        if (arrM[0] < 0) {
            break;
        }
        counter += 1;
    }
    if (Arr[i] == 100) {
        arrM[2] += 1;
        arrM[1] -= 1;
        arrM[0] -= 1;
        if (arrM[0] < 0 || arrM[1] < 0) {
            break;
        }
        counter += 1;
    }
}
if (counter == arrLen) {
print("YES");
}
else {
print("NO");
}

;(function () {

readline();

var m = readline().split(' ').map(Number);

var t = 0;

for (var i = 0; i < m.length; i++)
 if (m[i] == 25) t++;
 else {
  if (m[i] == 50 && t > 0) t--;
  else if (m[i] == 100 && t > 1) t -= 2;
  else {
   print('NO');
   return;
  }
 }

print('YES');

}).call(this);

const fs = require('fs')

const readStdin = () => {
  return new Promise((resolve, reject) => {
    fs.readFile(0, (err, data) => {
      if (err) {
        reject(err)
      } else {
        resolve(data.toString())
      }
    })
  })
}

async function main () {
  const str = await readStdin()
  const lines = str.split('\n')
  const n = parseInt(lines[0])
  const bills = lines[1].split(' ').map(token => parseInt(token))

  let _25 = 0
  let _50 = 0
  let could = true

  bills.forEach((bill) => {
    if (bill === 25) {
      _25++
    } else if (bill === 50) {
      _50++
      if (_25 === 0) {
        could = false
        _25--
      }
    } else {
      if (_50 > 0) {
        _50--
        if (_25 === 0) {
          could = false
          _25--
        }
      } else if (_25 === 3) {
        _25 -= 3
      } else {
        could = false
      }
    }
  })

  if (could) {
    console.log('YES')
  } else {
    console.log('NO')
  }
}

main().then(() => {})

const fs = require('fs')

const readStdin = () => {
  return new Promise((resolve, reject) => {
    fs.readFile(0, (err, data) => {
      if (err) {
        reject(err)
      } else {
        resolve(data.toString())
      }
    })
  })
}

async function main () {
  const str = await readStdin()
  const lines = str.split('\n')
  const n = parseInt(lines[0])
  const bills = lines[1].split(' ').map(token => parseInt(token))

  let _25 = 0
  let _50 = 0
  let could = true

  bills.forEach((bill) => {
    if (bill === 25) {
      _25++
    } else if (bill === 50) {
      _50++
      if (_25 === 0) {
        could = false
      } else {
        _25--
      }
    } else {
      if (_50 > 0) {
        _50--
        if (_25 === 0) {
          could = false
          _25--
        }
      } else if (_25 === 3) {
        _25 -= 3
      } else {
        could = false
      }
    }
  })

  if (could) {
    console.log('YES')
  } else {
    console.log('NO')
  }
}

main().then(() => {})