---
# System prepended metadata

title: Java_Cmoney_ft9108_找出連續正整數_改1
tags: [Cmoney_Java題目]

---

---
tags: Cmoney_Java題目
---
Java_Cmoney_ft9108_找出連續正整數_改1
===
==如果有一樣長的數字也要輸出 -1 ，
另外會直接輸入數列並以逗點分隔，
例如" 1 , -2, 3, 5 "==
![](https://i.imgur.com/jrjGNkZ.png)




1.主程式
---
使用迴圈找最長正整數序列
1. 利用 `ArrayList<Integer> sameMax` 記錄所有的 maxCount ，如果最後一個和倒數第二個一樣，代表最長的長度出現兩次以上

    
```java=
import java.util.ArrayList;
import java.util.Scanner;

public class test06 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();

        /* Split String */
        String[] strSplit = str.split(",");

        /* String[] to int[] */
        int[] numbers = new int[strSplit.length];
        for (int i = 0; i < strSplit.length; i++) {
            numbers[i] = Integer.valueOf(strSplit[i]);
        }

        /* find maximum continuous positive sequence in Array */
        ArrayList<Integer> sameMax = new ArrayList<>();/* save all maximum */
        int maxCount = 0, maxIndex = 0, count = 0, curIndex = 0;
        for (int i = 0; i < numbers.length; i++) {
            if (numbers[i] > 0) {
                count++;
                if (count == 1)
                    curIndex = i;
            } else {
                count = 0;
            }
            if (count >= maxCount) {
                maxCount = count;
                maxIndex = curIndex;
                sameMax.add(maxCount);
            }
        }

        /* print */
        int sum = 0;
        /* when there are two maximum print -1 */
        if(sameMax.size() == 1)
            System.out.println(-1);
        else if (sameMax.get(sameMax.size() - 1) == sameMax.get(sameMax.size() - 2))
            System.out.println(-1);
        else {
            for (int i = maxIndex; i < maxIndex + maxCount; i++) {
                sum += numbers[i];
            }
            System.out.println(sum);
        }
    }
}




```

