Dynamic Programming
Dynamic Programming
Given an array of numbers, find the index of the smallest array element (the pivot), for
which the sums of all elements to the left and to the right are equal. The array may not
be reordered.
Example
arr=[1,2,3,4,6]
● The sum of the first three elements, 1+2+3=6. The value of the last element is 6.
● Using zero based indexing, arr[3]=4 is the pivot between the two subarrays.
● The index of the pivot is 3.
Constraints
● 3 ≤ n ≤ 10^5
● 1 ≤ arr[i] ≤ 2 × 10^4, where 0 ≤ i < n
● It is guaranteed that a solution always exists.
Input format:
The first line contains an integer n, the size of the array arr.
Each of the next n lines contains an integer, arr[i], where 0 ≤ i < n.
Output format:
Print an integer representing the index of the pivot
Sample Input
4 → arr[] size n = 4
1 → arr = [1, 2, 3, 3]
2
3
3
Sample Output
2
Explanation
● The sum of the first two elements, 1+2=3. The value of the last element is 3.
● Using zero based indexing, arr[2]=3 is the pivot between the two subarrays.
● The index of the pivot is 2.
1
Solution:
#include <stdio.h>
int main(void) {
int n,i,j,sum=0;
scanf("%d",&n);
int arr[n],pr[n];
for(i=0;i<n;i++){
scanf("%d",&arr[i]);
sum += arr[i];
pr[i] = sum;
}
for(i=1;i<n;i++){
if(pr[i-1]==sum-pr[i]){
printf("%d",i);
break;
}
}
return 0;
}
Constraints:
● 1 ≤ n ≤ 106
● −107 ≤ arr[i] ≤ 107
Input Format:
The first line contains an integer n, the size of the array arr.
Each of the next n lines contains an integer arr[i].
Sample Input:
4
-1
-2
2
1
3
Sample Output:
4
Explanation:
The maximum sum for any contiguous subarray in [−1, −2, 1, 3] is 1 + 3 = 4.
Solution:
#include <stdio.h>
int main(void) {
int n,i;
scanf("%d",&n);
int a[n];
for(i=0;i<n;i++){
scanf("%d",&a[i]);
}
int max_so_far = a[0];
int curr_max = a[0];
}
printf("%d",max_so_far);
return 0;
}
3
For example, your array s = [1, 2, 2, 3, 1, 6]. Two examples of strictly increasing
subsequences of that array are (1,2), (1, 2, 3). Note that the 2 cannot repeat in the
second subsequence as 2 ≮ 2. The longest increasing subsequence has a length of 4:
LIS = [1,2,3,6].
Constraints:
● 1 ≤ n < 1000
● 1 ≤ s[i] ≤ 1000000
Input Format:
The first line contains an integer n, the size of the array s.
Each of the next n lines contains an integer s[i] where 1 ≤ i ≤ n.
Sample Input:
3 → s[] Size = 3
1 → s[] = [ 1,
4 4,
3 3]
Sample Output:
2
Explanation:
Inputs are s=[1,4,3]. Increasing subsequences are [1,4] and [1,3].
The longest increasing subsequence has 2 elements.
Solution:
#include <stdio.h>
int main(void) {
int n,i;
scanf("%d",&n);
int nums[n],dp[n];
for(i=0;i<n;i++){
scanf("%d",&nums[i]);
dp[i] = 1;
}
int maxSequence = 1;
int temp = 1;
for(int i=n-2;i>=0;i--){
temp = 1;
4
for(int j=i+1;j<n;j++){
if(nums[j]>nums[i]){
if(temp<1+dp[j]){
temp = 1+dp[j];
}
}
}
dp[i] = temp;
if(temp>maxSequence){
maxSequence = temp;
}
}
printf("%d",maxSequence);
return 0;
}