You are given an integer that is represented in the form of a string of length. You can remove at most 1 digit from the number after removing the rest of the digits that are arranged in the same order.
Example
For N = 2134, if you delete the digit 3, the new number is 214.
You are also given an integer K. Find the maximum possible value of (N mod K ) after deleting at most 1 digit from the number N.
Example:
Input: n = 5, k = 12 , str = "52436"
Output: 11
Approach
Java
public class MaxModuloFun {public static void main(String args[]) throws Exception {int n = 5;int k = 12;char ch[] = "52436".toCharArray();long res = maximumModuleFunction(n, k, ch);System.out.println(res);}private static long maximumModuleFunction(int n, int k, char[] ch) {long res = 0;long pre[] = new long[n];for (int i = 0; i < n; i++) {ch[i] -= '0';res = (res * 10 + ch[i]) % k;pre[i] = res;}long reg = 0, p = 1;for (int i = n - 1; i >= 0; --i) {long cur = ((i - 1 >= 0 ? pre[i - 1] : 0) * p + reg) % k;res = Math.max(res, cur);reg = (p * ch[i] + reg) % k;p = p * 10 % k;}return res;}}
C++
#include <bits/stdc++.h>using namespace std;long maximumModuleFunction(int n, int k, string str){long res = 0;vector<long> pre(n);for (int i = 0; i < n; i++){str[i] -= '0';res = (res * 10 + str[i]) % k;pre[i] = res;}long reg = 0, p = 1;for (int i = n - 1; i >= 0; --i){long cur = ((i - 1 >= 0 ? pre[i - 1] : 0) * p + reg) % k;res = max(res, cur);reg = (p * str[i] + reg) % k;p = p * 10 % k;}return res;}int main(){int n = 5, k = 12;string str = "52436";cout << maximumModuleFunction(n, k, str) << "\n";return 0;}
No comments:
Post a Comment