Open In App

Optimizing K for Maximum Sum in Array

Last Updated : 02 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array A[] of size N. You have to choose a number K between 1 and N (inclusive). Your score will be the sum of all the elements A[i] such that i is a multiple of K, the task is to find the minimum value of K with the maximum sum.

Examples:

Input: N = 2, A[] = {-3, 4}
Output: 2
Explanation: If we take K = 1, the score would be A1 + A2 = -3 + 4 = 1 but if we take K = 2 the score would be A2 = 4. So 2 is the correct choice.

Input: N = 3, A[] = {1, 2, 4 }
Output: 1
Explanation: Optimal to choose K = 1, such that sum becomes 1 + 2 + 4 = 7

Approach: This can be solved with the following idea:

Iterating in array A, for each i we have to calculate the sum of elements involved in each iteration. Store that sum in the maximum sum.

Below are the steps involved:

  • Iterate in Array A, where i would be the value for K.
  • For each i, run a loop for where starting would be j = i -1 and increment the value by i.
  • Store the value of elements in sum. Update the value sum in max and update k accordingly.

Below is the implementation of the code:

C++




// C++ Implementation
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
 
// Function to find minimum K and maximum
// sum
long long solve(int n, vector<long long> A)
{
    // Intialize it with maximum sum
    long long ans = -1e18;
    long long k = 0;
 
    // Iterate in loop
    for (int i = 1; i <= n; i++) {
        long long sum = 0;
 
        // Check for for each K possible value
        for (int j = i - 1; j < n; j = j + i) {
            sum = sum + A[j];
        }
 
        // Update the maximum sum
        if (sum > ans) {
            k = i;
            ans = sum;
        }
    }
 
    // Return K with maximum possible sum
    return k;
}
 
// Driver code
int main()
{
 
    int N = 5;
    vector<long long> A = { 1, 2, 3, 3, 1 };
 
    // Function call
    cout << solve(N, A);
    return 0;
}


Java




import java.util.*;
 
public class Main {
     
    // Function to find minimum K and maximum sum
    static long solve(int n, ArrayList<Long> A) {
        // Initialize it with maximum sum
        long ans = Long.MIN_VALUE;
        long k = 0;
 
        // Iterate in loop
        for (int i = 1; i <= n; i++) {
            long sum = 0;
 
            // Check for each K possible value
            for (int j = i - 1; j < n; j = j + i) {
                sum = sum + A.get(j);
            }
 
            // Update the maximum sum
            if (sum > ans) {
                k = i;
                ans = sum;
            }
        }
 
        // Return K with maximum possible sum
        return k;
    }
 
    // Driver code
    public static void main(String[] args) {
        int N = 5;
        ArrayList<Long> A = new ArrayList<>(Arrays.asList(1L, 2L, 3L, 3L, 1L));
 
        // Function call
        System.out.println(solve(N, A));
    }
}


Python3




# Python implementation
# Function to find minimum K and maximum sum
def solve(n, A):
    # Intialize it with maximum sum
    ans = -1e18
    k = 0
 
    # Iterate in loop
    for i in range(1, n+1):
        sum = 0
 
        # Check for for each K possible value
        for j in range(i-1, n, i):
            sum = sum + A[j]
 
        # Update the maximum sum
        if sum > ans:
            k = i
            ans = sum
 
    # Return K with maximum possible sum
    return k
 
# Driver code
N = 5
A = [1, 2, 3, 3, 1]
 
# Function call
print(solve(N, A))
 
# This code is contributed by Tapesh(tapeshdua420)


C#




using System;
 
public class MaxSumKValue
{
    // Function to find the 'k' value that results in the maximum possible sum
    public static int Solve(int n, int[] A)
    {
        long ans = long.MinValue; // Initialize 'ans' with a very small value
        int k = 0; // Initialize 'k' with 0
 
        for (int i = 1; i <= n; i++)
        {
            long sum = 0; // Initialize 'sum' to calculate the sum of values for each 'k'
 
            // Check for each 'k' possible value
            for (int j = i - 1; j < n; j += i)
            {
                sum += A[j]; // Add the value at index 'j' to 'sum'
            }
 
            // Update 'k' and 'ans' if the current 'sum' is greater than the previous maximum
            if (sum > ans)
            {
                k = i;
                ans = sum;
            }
        }
 
        // Return the 'k' value with the maximum possible sum
        return k;
    }
 
    public static void Main(string[] args)
    {
        const int N = 5; // Number of elements in the array
        int[] A = { 1, 2, 3, 3, 1 }; // Array of elements
 
        // Call the 'Solve' function to find the 'k' value with the maximum sum
        int result = Solve(N, A);
 
        Console.WriteLine(result); // Print the result (the value of 'k') to the console
    }
}


Javascript




// Function to find the 'k' value that results in the maximum possible sum
function solve(n, A) {
    let ans = -1e18;  // Initialize 'ans' with a very small value
    let k = 0;        // Initialize 'k' with 0
 
    for (let i = 1; i <= n; i++) {
        let sum = 0;   // Initialize 'sum' to calculate the sum of values for each 'k'
 
        // Check for each 'k' possible value
        for (let j = i - 1; j < n; j += i) {
            sum += A[j];  // Add the value at index 'j' to 'sum'
        }
 
        // Update 'k' and 'ans' if the current 'sum' is greater than the previous maximum
        if (sum > ans) {
            k = i;
            ans = sum;
        }
    }
 
    // Return the 'k' value with the maximum possible sum
    return k;
}
 
const N = 5;                // Number of elements in the array
const A = [1, 2, 3, 3, 1];  // Array of elements
 
// Call the 'solve' function to find the 'k' value with the maximum sum
const result = solve(N, A);
 
console.log(result);  // Print the result (the value of 'k') to the console


Output

1







Time Complexity: O(N2)
Auxiliary Space: O(1)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads