here I am trying to convert my recursive solution into a dynamic solution but I am getting problem in converting. I am trying to count minimum possible coin to make value. what I am doing is I am taking all possible coin and putting inside a vector and finally in main function I will find and minimum of my vector and that will be my answer
int rec(vector<int>coins,int n,int sum,int counter)
{
if(sum==0)
{
return 1;
}
if(n==0)
{
return 0;
}
int total=rec(coins,n-1,sum,counter);
if(sum-coins[n-1]>=0)
{
total+=rec(coins,n,sum-coins[n-1],counter+1);
if(sum-coins[n-1]==0)
{
vec.push_back(counter+1);
}
}
return total;
}
you should first try to solve this type of problems by yourself.
BTW:
#define BIG 2147483647
int min_coin(int *coins, int m, int desire_value)
{
int dp[desire_value+1];
dp[0] = 0;
for (int i=1; i<=desire_value; i++)
dp[i] = BIG;
for (int i=1; i<=desire_value; i++)
{
for (int j=0; j<m; j++)
if (coins[j] <= i)
{
int diff = dp[i-coins[j]];
if (diff != BIG && diff + 1 < dp[i])
dp[i] = diff + 1;
}
}
if(dp[desire_value]==BIG)
return -1;
return dp[desire_value];
}
you can easily convert dp and coins to vector. vector is like array.(beware for allocate vector for dp you should reserve space in vector see here.)
This is the code for the Triangle problem in codility that is throwing me an arithmetic overflow error.
int solution(vector<int> &A) {
int i, n;
n=A.size();
sort(A.begin(), A.end());
for(i=0; i<n-2; i++)
{
if((A[i]+A[i+1]>A[i+2])&&(A[i]+A[i+2]>A[i+1])&&(A[i+1]+A[i+2]>A[i]))
{
return 1;
}
}
return 0;
}
It passes all the tests except for the 'extreme_arith_overflow1 overflow test, 3 MAXINTs' saying the code returns 0 but it expects 1. Anybody have any idea on how to fix this?
You store A.size() in n and then you loop until i<n and access A[i+2]. In the error cases this is A[A.size()] or even A[A.size()+1]. It's out of bounds. Fix the range of the loop.
The next problem occurs when the sum is larger than INT_MAX. Use the difference instead of the sum to avoid overflow. Remember that the elements are sorted with A[i] <= A[i+1] <= A[i+2]
int solution(vector<int> &A) {
if (A.size() < 3) return 0;
const auto n = A.size() - 2;
std::sort(A.begin(), A.end());
for(decltype(n) i = 0; i < n; ++i) {
if((A[i]>A[i+2]-A[i+1])&&(A[i+2]>A[i+1]-A[i])&&A[i]>0) {
return 1;
}
}
return 0;
}
I'm trying to write a function that finds the number of prime numbers in an array.
int countPrimes(int a[], int size)
{
int numberPrime = 0;
int i = 0;
for (int j = 2; j < a[i]; j++)
{
if(a[i] % j == 0)
numbPrime++;
}
return numPrime;
}
I think what I'm missing is I have to redefine i after every iteration, but I'm not sure how.
You need 2 loops: 1 over the array, 1 checking all possible divisors. I'd suggest separating out the prime check into a function. Code:
bool primeCheck(int p) {
if (p<2) return false;
// Really slow way to check, but works
for(int d = 2; d<p; ++d) {
if (0==p%d) return false; // found a divisor
}
return true; // no divisors found
}
int countPrimes(const int *a, int size) {
int numberPrime = 0;
for (int i = 0; i < size; ++i) {
// For each element in the input array, check it,
// and increment the count if it is prime.
if(primeCheck(a[i]))
++numberPrime;
}
return numberPrime;
}
You can also use std::count_if like this:
std::count_if(std::begin(input), std::end(input), primeCheck)
See it live here.
For an array A of arbitrary length n, I'd like to fill in a n x m array B with all combination of elements from A that includes all possible orders of those elements. For example, if A = {1, 2, 3} and m = 2, I'd like to get B as:
11
12
13
21
22
23
31
32
33
What is an efficient way to do this in C/C++? Thanks!
EDIT: Here is what I figured out to work (data is within the class combs which is basically a matrix class with some added tricks):
void combs::setCombs (int arr[], int n, int m) {
int z, tmp, repeat;
int max = (int (pow(double (n), double( m ))));
for (int i = 0; i < m; i++) {
z = 0;
repeat = int (pow( double (n), double (i)));
for (int j = 0; j < repeat; j++) {
for (int k = 0; k < n; k ++) {
for (int p = 0; p < max/(n*repeat); p ++) {
cout << arr[k] << endl;
data[z*ROWS + i] = arr[k];
z++;
}
}
}
}
}
As mentioned by #Joachim Pileborg your question lacks a lot in the way of parameters.But lets say you could guarantee that you were passing me a vector of SORTED UNIQUE ints. Then this brute force would be possible:
std::vector< std::string > Combo( const std::vector< char >& source, int m )
{
std::vector< std::vector< char >::const_iterator > digits( length, source.cbegin() );
std::vector< std::string > result( source.size() * m );
for( int i = 0; i < result.size(); i++ )
{
for( int j = 0; j < m; j++ )
{
result[i] += *(digits[j]);
}
for( int j = digits.size() - 1; j >= 0; j-- )
{
++digits[j];
if( digits[j] == source.cend() )
{
digits[j] = source.cbegin();
}
else
{
break;
}
}
}
return result;
}
What you are describing sounds like partial permutations, not combinations.
If you are using c++, then it is recommended to use vectors, because vectors can tell you their size, and they free their own memory. An implementation with vectors would be as follows:
vector<vector<int> > partialPermutations(vector<int> &A,int m){
int i,i2,t,n=A.size(),total=1;
for(i=0;i<m;i++) total*=n;
vector<vector<int> > result;
for(i=0;i<total;i++){
result.push_back(vector<int>());
t=i;
for(i2=0;i2<m;i2++){
result[i].push_back(A[t%n]);
t/=n;
}
}
return result;
}
int main() {
vector<int> A;
int total,i,i2;
for(i=1;i<=4;i++) A.push_back(i);
vector<vector<int> > re=partialPermutations(A,2);
for(i=0;i<re.size();i++){
for(i2=0;i2<2;i2++)
cout<<re[i][i2]<<" ";
cout<<endl;
}
return 0;
}
If you still want to use arrays, then the code would be as follows:
int** partialPermutations(int*A,int n,int m,int &total){
int i,i2,t;
total=1;
for(i=0;i<m;i++) total*=n;
int **result=new int*[total];
for(i=0;i<total;i++){
t=i;
result[i]=new int[m];
for(i2=0;i2<m;i2++){
result[i][i2]=A[t%n];
t/=n;
}
}
return result;
}
int main() {
int A[]={1,2,3,4};
int total,i,i2;
int **re=partialPermutations(A,4,2,total);
for(i=0;i<total;i++){
for(i2=0;i2<2;i2++)
cout<<re[i][i2]<<" ";
cout<<endl;
}
//Cleanup
for(i=0;i<total;i++) delete[] re[i];
delete[] re;
return 0;
}
Notice that by using arrays, we have to recover the size of the resulting array (passing total by reference), and we have to free the memory afterwards. None of this is needed with vectors.
#include<iostream>
using namespace std;
void printStrRec(string s,string ans,int k,int i)
{
if(i==k)
{
cout<<"\nAnswer : "<<ans<<endl;
}
else
{
for(int x=0;x<s.size();++x)
{
ans[i]=s[x];
printStrRec(s,ans,k,i+1);
}
}
}
void printStrings(string s,int k)
{
string ans;
for(int p=0;p<k;++p)
{
ans+="x";
}
printStrRec(s,ans,k,0);
}
int main()
{
int k;
string s;
cout<<"Enter the set : ";
cin>>s;
cout<<"\nEnter k : ";
cin>>k;
printStrings(s,k);
return 0;
}
Hope that helps.
int array[] = {-1, 4, -2, 5, -5, 2, -20, 6};
If I had that array, my Kadane algorithm implementation to find the maximum subarray works:
int max_so_far = INT_MIN;
int max_ending_here = 0;
for (int i = 0; i < size; i++) {
max_ending_here = max(max_ending_here + array[i], 0);
max_so_far = max(max_ending_here, max_so_far);
}
printf("%d\n", max_so_far);
However, if I have an array of all negatives:
int array[]= {-10, -10, -10};
It won't work, it should return -10, but I get 0.
How can I make it work for negative numbers too?
Thank you!
When all elements are negative, the maximum subarray is the empty subarray, which has sum 0.
But if you want to change the algorithm to store the greatest element in this case, you could do the following:
int max_so_far = INT_MIN;
int max_ending_here = 0;
int max_element = INT_MIN;
for (int i = 0; i < size; i++)
{
max_ending_here = max(max_ending_here + array[i], 0);
max_so_far = max(max_ending_here, max_so_far);
max_element = max(max_element, array[i]);
}
if (max_so_far == 0)
max_so_far = max_element;
printf("%d\n", max_so_far);
According to Wikipedia, Kadane's Algorithm requires at least one positive number, so your all negative array is invalid input.
int max_so_far = INT_MIN;
int max_ending_here = array[0];
for (int i = 1; i < size; i++) {
max_ending_here = max(max_ending_here + array[i], array[i]);
max_so_far = max(max_ending_here, max_so_far);
}
printf("%d\n", max_so_far);
It may works
Make a slight addition to Kadane's algo.
Take a flag, are_all_elements_negative(set to true) and an int(store the highest -ve integer)
while iterating over the array, if you find a positive number, set the flag false.
While the flag is true, store the highest -ve num. At the end,check the flag, if the flag is true,output the -ve integer, else output the regular Kadane's algo output.
Well Kadane's algorithm does not work for the case when all the elements of an array are negative. It simply returns 0 in that case. In case if you wanted the for handling this we need to add extra phase before actual implementation. The phase will look if all numbers are negative, if they are it will return maximum of them (or smallest in terms of absolute value).
I can suggest one implementation
#define find_max_val(x,y) x >= y ?x :y;
int min_sum(int a[],int n){
int min_so_far = a[0],min_end_here = a[0];
for(int i = 1;i < n; i++){
min_end_here = find_max_val(a[i],min_end_here + a[i]);
min_so_far = find_max_val(min_so_far,min_end_here);
}
return min_so_far;
}
there are still other implementations depending upon ones need.
if we have an array of all negatives, then the max element in the array will be the result.
For eg : if the array elements are -3 -2 -5 -4 -1
The largest sum subarray is -1.
just an O(n) search.
Code:
int maxSubArraySum(int array[], int size) {
int max_sum = INT_MIN, max_ending_here = 0;
for (int i = 0; i < size; i++) {
max_ending_here += a[i];
if (max_sum < max_ending_here) {
max_sum = max_ending_here;
}
max_ending_here = max(max_ending_here, 0);
}
return max_sum;
}
If all the elements are negative, then return the least negative number.
In all other cases, your solution will work just fine.
printf("%d\n",max(max_so_far, *max_element(array,array+size)) );
According to WIKI
public int maxSubArray(int[] nums) {
int currentSum = 0;
int bestSum = 0;
for (int element : nums) {
currentSum = Math.max(0, currentSum + element);
bestSum = Math.max(bestSum, currentSum);
}
return bestSum;
}
The above code will fail for the input
nums = [-1]
According to WIKI again
This version of the algorithm will return 0 if the input contains no positive elements (including when the input is empty). For the variant of the problem which disallows empty subarrays, best_sum should be initialized to negative infinity instead and also in the for loop current_sum should be updated as max(x, current_sum + x). In that case, if the input contains no positive element, the returned value is that of the largest element (i.e., the least negative value), or negative infinity if the input was empty.
Modified code for negative inputs:
public int maxSubArray(int[] nums) {
int currentSum = 0;
int bestSum = Integer.MIN_VALUE;
for (int element : nums) {
currentSum = Math.max(element, currentSum + element);
bestSum = Math.max(bestSum, currentSum);
}
return bestSum;
}
Please refer to wikiped kadane's algorithm max subarray
int max_subArray(Integer[] input){
int max_so_far,max_ending_here;
max_so_far = max_ending_here =input[0];
for(int i =1; i<input.length;i++){
max_ending_here = Math.max(input[i], input[i]+max_ending_here);
max_so_far = Math.max(max_so_far, max_ending_here);
}
return max_so_far;
}
And it will return -10 in your case
This is another option for achieving your goal
int Solution::maxSubArray(const vector<int> &A){
int cs=0,ms=0,l=A.size(),x=0,min;
if(A[0]<0)
min=A[0];
x++;
if(l==1)
return A[0];
for(int i=1;i<A.size();i++){
if(A[i]<0)
x++;
if(A[i]>min)
min=A[i];
else
break;
}
if(x==l)
return min;
for(int i=0;i<A.size();i++){
cs=cs+A[i];
if(cs<0)
cs=0;
ms=max(cs,ms);
}
return ms;
}
Here is my approach, have used extra 2 variables
public int maxSubArray(int[] nums) {
int max_so_far = 0;
int max_ends_here = 0;
int largestNeagtive = Integer.MIN_VALUE;
boolean isAllNegativeNumbers = true;
for (int i = 0; i < nums.length; i++) {
max_ends_here += nums[i];
if (max_ends_here < 0) max_ends_here = 0;
if (max_so_far < max_ends_here) max_so_far = max_ends_here;
if (isAllNegativeNumbers && nums[i] >= 0) isAllNegativeNumbers = false;
if (nums[i] < 0 && nums[i] > largestNeagtive) largestNeagtive = nums[i];
}
return isAllNegativeNumbers ? largestNeagtive : max_so_far;
}
Refer this excellent explanation of Kadane's algorithm which will work for all negative numbers case as well.
go implementation is here:
func maxSubArrayKadane(nums []int) int {
// Validate input
var n = len(nums)
if n == 0 {
return 0
}
if n == 1 {
return nums[0]
}
var localMax = 0
var globalMax = math.MinInt
for _, val := range nums {
localMax = max(val, localMax+val)
if localMax > globalMax {
globalMax = localMax
}
}
return globalMax
}
func max[T constraints.Ordered](a, b T) T {
if a > b {
return a
}
return b
}
I'm late to this party, but would something like this work?:
cur_sum = max_sum = sequence[0];
sum_to_j = 0;
for j in range(0, len(sequence)):
sum_to_j += sequence[j];
if sum_to_j > cur_sum:
cur_sum = sum_to_j;
if cur_sum > max_sum:
max_sum = cur_sum
if sum_to_j < 0:
sum_to_j = 0;
cur_sum = sequence[j];
print max_sum;
If all the elements are negative,Return the largest element by value
boolean allNegative = true;
int bigNegative = Integer.MIN_VALUE;
int maxSum = 0;
int sum = 0;
for(int i=0;i<a.size();i++){
// if all numbers are negative
if(a.get(i)>=0){
allNegative = false;
}else{
if(a.get(i)>bigNegative){
bigNegative = a.get(i);
}
}
sum += a.get(i);
if(sum<0){
sum=0;
}
if(sum>maxSum){
maxSum = sum;
}
}
if(allNegative){
return bigNegative;
}
return maxSum;
It works with the below code.
public int algorithmKadane(int[] input_array){
int sum = input_array[0];
int rotate_sum = input_array[0];
for(int i=1; i< input_array.length ; i++){
rotate_sum = Math.max(input_array[i], rotate_sum+input_array[i]);
sum = Math.max(rotate_sum,sum);
}
return sum;
}
Hope this solution would work to handle all negative numbers case too for Kadane's Algo
long long int n,max_f=0,i,max_end=0,s;
cin>>n;
long long int a[n];
for(i=0;i<n;i++)
{
cin>>a[i];
}
long long int *m;
m=max_element(a,a+n);
if(*m<0)
{
s=*m;
}
else {
for(i=0;i<n;i++)
{
max_end= max_end +a[i];
if(max_end<0)
{
max_end=0;
}
if(max_f < max_end)
{
max_f=max_end;
}
s=max_f;
}
}
cout<<s<<endl;
}
public static int max_sum(int[] in){
int maxsum=0;
int cursum=0;
for (int i=0;i<in.length;i++){
cursum = in[i]+cursum;
if (cursum>maxsum) {
maxsum = cursum;
}
// for negative value
if (cursum < 0) {
for (int n=0;n<in.length;n++){
maxsum = in[n];
if (cursum>maxsum){
maxsum=cursum;
}
}
}
}
return maxsum;
}
int maxSub(vector<int> x){
int current_max=0,overall_max=INT_MIN;
for(int i=0;i<x.size();i++){
current_max+=x[i];
if(overall_max<current_max)
overall_max=current_max;
if(current_max <0)
current_max=0;
}
return overall_max;
}