从两侧选择?

huangapple go评论85阅读模式
英文:

Pick from both sides?

问题

以下是翻译好的代码部分:

public class Solution {
    ArrayList<Integer> c = new ArrayList<>();
    ArrayList<Integer> A = new ArrayList<>();

    public int solve(ArrayList<Integer> A, int B) {
        if (B > A.size()) {
            int sum = 0;
            for (int i = 0; i < A.size(); i++)
                sum = sum + A.get(i);
            return sum;
        }

        int max_sum = 0;
        for (int i = 0; i < A.size(); i++) {
            if ((max_sum < suffix(A.size() - (B - i)) + prefix(i - 1))) {
                max_sum = suffix(A.size() - (B - i)) + prefix(i - 1);
            }
        }
        return max_sum;
    }

    int prefix_sum = 0;
    int prefix(int a) {
        for (int p = 0; p < a + 1; p++) {
            c = A;
            prefix_sum = prefix_sum + c.get(p);
        }
        return prefix_sum;
    }

    int suffix_sum = 0;
    int suffix(int b) {
        c = A;
        for (int q = b; q < c.size(); q++) {
            suffix_sum = suffix_sum + c.get(q);
        }
        return suffix_sum;
    }
}

希望这对你有所帮助。如果你继续遇到问题,请随时问我。

英文:

The problem statement is :
Given an integer array A of size N.

You can pick B elements from either left or right end of the array A to get maximum sum.
Find and return this maximum possible sum.

NOTE: Suppose B = 4 and array A contains 10 elements then:

You can pick first four elements or can pick last four elements or can pick 1 from front and 3 from back etc . you need to return the maximum possible sum of elements you can pick.

public class Solution {
ArrayList&lt;Integer&gt; c = new ArrayList&lt;&gt;();
ArrayList&lt;Integer&gt; A= new ArrayList&lt;&gt;();
public int solve(ArrayList&lt;Integer&gt; A, int B) {
if (B&gt;A.size()){
int sum=0;
for(int i=0;i&lt;A.size();i++)
sum= sum+A.get(i);
return sum;
}
int max_sum=0;
for(int i=0;i&lt;A.size();i++){
if((max_sum&lt;suffix(A.size()-(B-i))+prefix(i-1)) ){
max_sum=suffix(A.size()-(B-i))+prefix(i-1);
}
}
return max_sum;
}
int prefix_sum=0;
int prefix(int a)   {
for(int p=0;p&lt;a+1;p++){
c=A;
prefix_sum=prefix_sum + c.get(p);
}
return prefix_sum;
}
int suffix_sum=0;
int suffix(int b){
c=A;
for(int q=b;q&lt;c.size();q++){
suffix_sum=suffix_sum+c.get(q);
}
return suffix_sum;
}

}

I am getting runtime error, I have tried to implement the suffix and prefix methods which return the sum from the index[ 0, i] and sum from [i, N-i] respectively, then in the solve function I am trying to find the sum of prefix [a-1] +suffix[N-(b-a)] and find out the maximum sum, the syntax is completely correct, there is something wrong with the logic I assume, please help me find the correct solution by correcting this code instead of providing an alternative method

答案1

得分: 4

package com.array;

import java.util.Arrays;
import java.util.List;

public class PickFromBothSides {

    public static void main(String[] args) {
        Integer[] arr = { 5, -2, 3, 1, 2 };
        System.out.println(solve(Arrays.asList(arr), 3));
    }

    public static int solve(List<Integer> A, int B) {
        int n = A.size();
        int result = 0;

        for (int i = 0; i < B; i++) {
            result += A.get(i);
        }

        int sum = result;

        for (int i = 0; i < B; i++) {
            sum -= A.get(B - 1 - i);
            sum += A.get(n - 1 - i);
            result = Math.max(result, sum);
        }

        return result;
    }
}
// Runtime O(n)
// Space complexity O(1)
英文:
	package com.array;
import java.util.Arrays;
import java.util.List;
public class PickFromBothSides {
public static void main(String[] args) {
Integer[] arr = { 5, -2, 3, 1, 2 };
System.out.println(solve(Arrays.asList(arr), 3));
}
public static int solve(List&lt;Integer&gt; A, int B) {
int n = A.size();
int result = 0;
for (int i = 0; i &lt; B; i++) {
result += A.get(i);
}
int sum = result;
for (int i = 0; i &lt; B; i++) {
sum -= A.get(B - 1 - i);
sum += A.get(n - 1 - i);
result = Math.max(result, sum);
}
return result;
}
}

Runtime O(n)
Space complexity O(1)

答案2

得分: 0

你正在将int prefix_sum = 0;int suffix_sum = 0; 声明为字段,而不是各自方法的局部变量。

你正在调用 suffix(A.size() - (B - i)),根据你的示例,这是 10 - (4 - i),即 6 + i。你在迭代中使用 i 在范围 {0, ..., 10} 内,所以值 6 + i 将是从 6 到 16 的所有数字。你不能在数组中以上标 9 进行索引,因此会出现异常。

你需要将

for(int i = 0; i < A.size(); i++){

改为

for(int i = 0; i <= B; i++){

因为你试图询问每次迭代“从开头开始取多少个数字”?如果 B 为 4,则是 0、1、2、3 或 4。


其他改进:

  1. 你两次连续调用了 suffix(A.size() - (B - i)) + prefix(i - 1))。只需调用一次,将其存储在变量中并重复使用。

  2. 你调用了 prefix(i - 1),但在 prefix() 内部,你将参数 a 设置为 a + 1。你没必要对同一项进行减一和加一的操作。

英文:

You are declaring int prefix_sum=0; and int suffix_sum=0; as fields, not as local variables of the respective methods.

You are calling suffix(A.size()-(B-i)) so with your example that is 10 - (4 -i) which is 6 + i. You iterate through i being in the range {0, ..., 10} so the value 6 + i will be all the numbers 6 through 16. You cannot index in the array above 9, so you get an exception.

You need to change

for(int i=0;i&lt;A.size();i++){

to

for(int i=0; i &lt;= B; i++){

because you are trying to ask each iteration "how many numbers are taken from the beginning"? 0, 1, 2, 3 or 4 if B is 4


Other upgrades:

  1. You are calling suffix(A.size()-(B-i))+prefix(i-1)) twice in a row. Call it only once, store it in a variable and reuse.

  2. You are calling prefix(i-1) but inside prefix() you are using the parameter a as a + 1. You don't need to subtract one and add one to the same thing

答案3

得分: 0

以下是用另一种方法解决这个问题的代码(使用Python3):

def solve(A, B):
    left = [0]
    for i in range(B):
        left.append(left[-1] + A[i])
    right = [0]
    for i in range(B):
        right.append(right[-1] + A[len(A) - i - 1])
    for i in range(B + 1):
        left[i] += right[B - i]
    return max(left)

在这里,我创建了数组A的左侧和右侧各包含B个元素的累积和(前缀和和后缀和),然后将左侧的第一个元素与右侧的最后一个元素的和相加。最终返回它们中的最大值。

英文:

PFB another approach to solve this problem(in Python3):

 def solve(A, B):
left = [0]
for i in range(B):
left.append(left[-1]+A[i])
right = [0]
for i in range(B):
right.append(right[-1]+A[len(A)-i-1])
for i in range(B+1):
left[i] += right[B-i]
return max(left)

Here I created a cumulative sum (or prefix and suffix sum) of B number of elements from the left and right sides of array A, Then added the sum of the first element of the left with the last element of the right. Thus finally returned the max of them.

huangapple
  • 本文由 发表于 2020年8月22日 22:47:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/63537467.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定