Snacks within 300 Yen
Source: aizu

Problem A
Snacks within 300 Yen

Your friend, Greedy George, visits a candy store for his snacks for the school excursion, grabbing 300 yen in his hand. In the candy store, one item of each different kind of snack is placed in a line on the shelf. After entering the store, Greedy George picks up a shopping basket and starts checking the snacks on the shelf from left to right. If the sum of the prices of snacks in the basket will not exceed 300 yen, he immediately puts the checked snack into the basket. If the sum should exceed 300 yen, he tearfully skips that snack. After examining all the snacks in this manner to the right end, George heads to the checkout.

Given a list of the prices of the snacks in the store, compute how much money Greedy George will spend.

Figure A-1: The first dataset of Sample Input
Input

The input consists of multiple datasets, each in the following format. The number of datasets does not exceed 50.

n
a1 a2 ⋯ an


n (1 ≤ n ≤ 100) is the number of snacks sold in the candy store. ak (k = 1, , n) is a positive integer less than or equal to 1000, meaning that the price of the k-th snack from the left is ak yen.

The end of the input is indicated by a line consisting of a zero.

Output

For each dataset, output in a line how many yen Greedy George will spend on the snacks.

Sample Input
5
100 50 200 120 60
4
120 240 180 1
2
500 1000
6
2 3 5 7 11 13
0

Output for the Sample Input
270
300
0
41


C++ solution:
#include<bits/stdc++.h>
using namespace std;
int main(){
    int n;
    while(true){
        cin >> n;
        if(n == 0) break;
        int a[n];
        int count=0;
        for(int i=0; i<n; i++){
            cin >> a[i];
            count += a[i];
            if(count > 300){
                count -= a[i];
            }
        }
        cout << count << endl;
    }
}

Go solution:
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	var results []int

	for {
		// Read number of snacks
		if !scanner.Scan() {
			break
		}
		nStr := strings.TrimSpace(scanner.Text())
		n, err := strconv.Atoi(nStr)
		if err != nil || n < 0 {
			continue
		}
		if n == 0 {
			break
		}

		// Read prices
		if !scanner.Scan() {
			break
		}
		pricesStr := strings.TrimSpace(scanner.Text())
		pricesSplit := strings.Fields(pricesStr)
		if len(pricesSplit) != n {
			continue
		}

		// Process prices
		total := 0
		for _, priceStr := range pricesSplit {
			price, err := strconv.Atoi(priceStr)
			if err != nil || price <= 0 {
				continue
			}
			if total+price <= 300 {
				total += price
			}
		}
		results = append(results, total)
	}

	// Output results
	for _, res := range results {
		fmt.Println(res)
	}
}

Java solution:
import java.util.*;
import java.io.*;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        List<Integer> results = new ArrayList<>();

        while (scanner.hasNext()) {
            if (!scanner.hasNextInt()) {
                scanner.next();
                continue;
            }
            
            int n = scanner.nextInt();
            if (n == 0) {
                break;
            }
            
            // Skip any remaining whitespace
            scanner.nextLine();
            
            // Read the prices line
            String line = scanner.nextLine();
            String[] pricesStr = line.split("\\s+");
            int[] prices = new int[n];
            for (int i = 0; i < n; i++) {
                prices[i] = Integer.parseInt(pricesStr[i]);
            }

            // Calculate spending
            int budget = 300;
            int spent = 0;
            for (int price : prices) {
                if (spent + price <= budget) {
                    spent += price;
                }
            }
            results.add(spent);
        }

        // Output results
        for (int result : results) {
            System.out.println(result);
        }
    }
}

JavaScript solution:
const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    terminal: false
});

let datasets = [];
let currentN = null;
let currentPrices = null;

rl.on('line', (line) => {
    const trimmed = line.trim();
    
    if (trimmed === '0') {
        rl.close();
        return;
    }
    
    if (currentN === null) {
        // This is an n line
        currentN = parseInt(trimmed, 10);
    } else {
        // This is a prices line
        currentPrices = trimmed.split(/\s+/).map(Number);
        
        // Verify we have the correct number of prices
        if (currentPrices.length === currentN) {
            datasets.push({
                n: currentN,
                prices: currentPrices
            });
        } else {
            // Handle case where prices count doesn't match n
            datasets.push({
                n: currentN,
                prices: currentPrices.slice(0, currentN)
            });
        }
        
        currentN = null;
        currentPrices = null;
    }
});

rl.on('close', () => {
    const results = [];
    
    for (const dataset of datasets) {
        let spent = 0;
        const budget = 300;
        
        for (const price of dataset.prices) {
            if (spent + price <= budget) {
                spent += price;
            }
        }
        
        results.push(spent);
    }
    
    // Print all results
    for (const result of results) {
        console.log(result);
    }
});

Python solution:
def Main():
    while True:
        n=int(input())
        if n==0:
            return
        a=list(map(int,input().split()))
        ans=0
        for x in a:
            if ans+x<=300:
                ans+=x
        print(ans)




Main()

Ruby solution:
while true
    n = gets.to_i
    break if n == 0
    sum = 0
    gets.chomp.split.map(&:to_i).each{|v|
        sum += v if sum + v <= 300
    }
    puts sum
end