β Max Candies (Contest)
Max Candies (Contest) easy Time Limit: 2 sec Memory Limit: 128000 kB
Problem Statement:
There is a row of N shops. Each shop sells A[i] candies. Your friend made an array B of (N-1) integers where B[i] = max(A[i], A[i+1]) for i from 1 to (N-1). You are given array B. You want to generate the array A such that the sum of values of the candies in A is maximum. Find the maximum possible sum of candies of array A. Input The first line of input contains a single integer N. The second line of input contains (N-1) integers denoting array B.
Constraints: 2 β€ N β€ 105 1 β€ B[i] β€ 109 Output Print the maximum possible sum of the candies in array A. Example Sample Input 4 1 3 4
Sample Output 9
Explanation: Optimal Array A will be [1, 1, 3, 4]
link:https://my.newtonschool.co/playground/code/oalw3xurv0ze/
```java
import java.io.*; // for handling input/output
import java.util.*; // contains Collections framework
// don't change the name of this class
// you can add inner classes if needed
class Main {
public static void main (String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int arr[]=new int[n-1];
long sum=0;
for(int i=0;i<n-1;i++){
arr[i]=sc.nextInt();
}
int A[]=new int[n];
A[0]=arr[0];
A[n-1]=arr[n-2];
sum +=A[0];
sum +=A[n-1];
for(int i=1;i<n-1;i++){
A[i]=Math.min(arr[i-1],arr[i]);
sum +=A[i];
}
System.out.println(sum);
}
}
```
Last updated