/******************************************************* * Copyright (C) 2015 Haotian Wu * * This file is the solution to the question: * https://www.hackerrank.com/challenges/maximise-sum * * Redistribution and use in source and binary forms are permitted. *******************************************************/ #include #include #include #include #include #include #include #include #include #include using namespace std; // First we compute the sum from arr[0] to arr[i] for all i's. We module m for every sum. // We can acquire a subarray sum by substracting sum[j] by sum[i] (j>i). In a special case, if we need the sum from arr[0] to arr[j], we just use sum[j]. // It's also possible sum[i] > sum[j] because of the module. In that case the subarray sum becomes (sum[j] + m - sum[i]). // Now the question becomes: For each sum[j], find the minimal sum[i] such that sum[i]>sum[j], i s; s.insert(m); long long maxi = -1; for (int i=0;i :: iterator it = s.lower_bound(sum[i]+1); long long diff = (sum[i]+m-(*it))%m; if (diff > maxi) maxi = diff; s.insert(sum[i]); } printf("%lld\n",maxi); } }