close
題目概要:
找出一個連續相乘為最大的值。Ex S={1,2,3,4,-4,2,-12} -4*2*-12=56。 Ps先由第一位數乘到最後一位數,再由由第二位數乘到最後一位數...依此類推找出最大值。
解題方向:
直接for迴圈運算即可。
程式碼:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Java | |
import java.util.Scanner; | |
class uva11059{ | |
public static void main(String args[]){ | |
Scanner sc=new Scanner(System.in); | |
int count=0; | |
while(sc.hasNextInt()){ | |
count++; | |
int n=sc.nextInt(); | |
int arr[]=new int[n]; | |
for(int i=0;i<n;i++) arr[i]=sc.nextInt(); | |
//找出最大值。 | |
long max=0; | |
for(int i=0;i<n;i++){ | |
long temp=1; | |
for(int j=i;j<n;j++){ | |
temp=temp*arr[j]; | |
if(max<temp) max=temp; | |
} | |
} | |
//Output | |
System.out.println("Case #"+count+": The maximum product is "+max+"."); | |
System.out.println(""); | |
} | |
} | |
} |
文章標籤
全站熱搜