📌  相关文章
📜  查找前缀总和大于后缀总和的 Array 的所有索引

📅  最后修改于: 2022-05-13 01:56:10.412000             🧑  作者: Mango

查找前缀总和大于后缀总和的 Array 的所有索引

给定一个包含N个整数的数组arr[] ,任务是除以找到所有索引,使得前缀总和(即范围[0, i)中的元素总和)大于后缀总和(范围[i, N-1] )

例子:

方法:基本思想是考虑每个索引并为此计算前缀和后缀总和。如果前缀总和大于后缀总和,则将此索引插入答案。

下面是上述方法的实现。

C++
// C++ code to implement the approach
#include 
using namespace std;
 
class Solution
{
  public:
  // Function to find the valid indices
  vector solve(vector& arr)
  {
    vector ans;
 
    // Total_size of the array
    int size = arr.size();
    int left_sum = 0;
    int total_sum = 0;
    for (auto dt : arr)
      total_sum += dt;
 
    // Upto second last index
    for (int idx = 0; idx < size - 1; ++idx) {
 
      // Add current element to
      // left_sum
      left_sum += arr[idx];
 
      // Calculate right_sum
      int right_sum = total_sum - left_sum;
 
      // Check condition
      if (left_sum > right_sum)
        ans.push_back(idx + 1);
    }
 
    return (ans);
  }
};
 
// Driver code
int main()
{
  Solution obj;
  vector arr = { 10, -3, 4, 6 };
  vector ans = obj.solve(arr);
  for (auto x : ans)
    cout << x << " ";
  return 0;
}
 
  // This code is contributed by rakeshsahnis


Java
// Java code to implement the approach
import java.util.*;
class GFG {
 
  // Function to find the valid indices
  static List solve(int arr[])
  {
    List ans = new ArrayList();
 
    // Total_size of the array
    int size = arr.length;
    int left_sum = 0;
    int total_sum = 0;
    for(int i = 0; i < size; i++){
      total_sum += arr[i];
    }
 
    // Upto second last index
    for (int idx = 0; idx < size - 1; ++idx) {
 
      // Add current element to
      // left_sum
      left_sum += arr[idx];
 
      // Calculate right_sum
      int right_sum = total_sum - left_sum;
 
      // Check condition
      if (left_sum > right_sum)
        ans.add(idx + 1);
    }
 
    return ans;
  }
 
  // Driver code
  public static void main (String[] args) {
    int arr[] = { 10, -3, 4, 6 };
    List ans = solve(arr);
    for (Integer x : ans)
      System.out.print(x + " ");
  }
}
 
// This code is contributed by hrithikgarg03188.


Python3
# Python code to implement the above approach
 
class Solution:
 
    # Function to find the indices
    def solve(self, arr):
        ans = []
 
        # Total_size of the array
        size = len(arr)
 
        # Upto second last index
        for idx in range(size-1):
            left_sum = 0
            right_sum = 0
 
            # Calculate left sum
            for left_idx in range(idx + 1):
                left_sum += arr[left_idx]
 
            # Calculate right sum
            for right_idx in range(idx + 1,
                                   size, 1):
                right_sum += arr[right_idx]
 
            # check condition
            if (left_sum > right_sum):
                ans.append(idx + 1)
 
        return(ans)
 
# Driver code
if __name__ == '__main__':
 
    obj = Solution()
    arr = [10, -3, 4, 6]
    ans = obj.solve(arr)
    for x in ans:
        print (x, end = " ")


C#
// C# code to implement the approach
using System;
using System.Collections;
 
class GFG {
 
    // Function to find the valid indices
    static ArrayList solve(int[] arr)
    {
        ArrayList ans = new ArrayList();
 
        // Total_size of the array
        int size = arr.Length;
        int left_sum = 0;
        int total_sum = 0;
        for (int i = 0; i < size; i++) {
            total_sum += arr[i];
        }
 
        // Upto second last index
        for (int idx = 0; idx < size - 1; ++idx) {
 
            // Add current element to
            // left_sum
            left_sum += arr[idx];
 
            // Calculate right_sum
            int right_sum = total_sum - left_sum;
 
            // Check condition
            if (left_sum > right_sum)
                ans.Add(idx + 1);
        }
 
        return ans;
    }
 
    // Driver code
    public static void Main()
    {
        int[] arr = { 10, -3, 4, 6 };
        ArrayList ans = solve(arr);
        foreach(int x in ans) Console.Write(x + " ");
    }
}
 
// This code is contributed by Samim Hossain Mondal.


Javascript


Python3
# Python code to implement the approach
 
class Solution:
 
    # Function to find the valid indices
    def solve(self, arr):
        ans = []
 
        # Total_size of the array
        size = len(arr)
        left_sum = 0
        total_sum = sum(arr)
 
        # Upto second last index
        for idx in range(size-1):
 
            # Add current element to
            # left_sum
            left_sum += arr[idx]
 
            # Calculate right_sum
            right_sum = total_sum - left_sum
 
            # Check condition
            if (left_sum > right_sum):
                ans.append(idx + 1)
 
        return(ans)
 
# Driver code
if __name__ == '__main__':
    obj = Solution()
    arr = [10, -3, 4, 6]
    ans = obj.solve(arr)
    for x in ans:
        print (x, end = " ")



输出
1 3 

时间复杂度: O(N 2 )
辅助空间: O(1)

Efficient Approach :上述方法可以通过基于以下思想计算数组的总和来进一步优化:

请按照以下步骤解决问题:

  • 迭代数组并求出数组的总和(比如总和)。
  • 初始化变量(比如 temp)以存储前缀总和。
  • i = 1 迭代到 N-1
    • arr[i-1]添加到前缀 sum。
    • 使用上述观察计算后缀和。
    • 如果前缀和后缀总和满足问题的条件,我将是答案之一。
  • 返回存储有效索引的数组。

下面是上述方法的实现。

Python3

# Python code to implement the approach
 
class Solution:
 
    # Function to find the valid indices
    def solve(self, arr):
        ans = []
 
        # Total_size of the array
        size = len(arr)
        left_sum = 0
        total_sum = sum(arr)
 
        # Upto second last index
        for idx in range(size-1):
 
            # Add current element to
            # left_sum
            left_sum += arr[idx]
 
            # Calculate right_sum
            right_sum = total_sum - left_sum
 
            # Check condition
            if (left_sum > right_sum):
                ans.append(idx + 1)
 
        return(ans)
 
# Driver code
if __name__ == '__main__':
    obj = Solution()
    arr = [10, -3, 4, 6]
    ans = obj.solve(arr)
    for x in ans:
        print (x, end = " ")


输出
1 3 

时间复杂度: O(N)
辅助空间: O(1)