881683. The Thief Problem

Easy

Here is a detailed Markdown blog post for the "The Thief Problem":

The Thief Problem

Summary

In this problem, we are given an array of integers and our task is to find the maximum sum of elements that can be obtained by selecting either all elements in the array or selecting all elements except one. This problem involves basic algorithmic concepts like arrays and loops.

Detailed Explanation

The problem seems quite simple at first glance, but it requires a good understanding of the given constraints. We are not allowed to skip more than one element from the array, which means we either select all elements or all elements except one.

To solve this problem, we can iterate through the array and calculate the sum of all elements. Then, we will subtract each element from the total sum to get the maximum sum that can be obtained by selecting all elements except one. We need to keep track of the maximum sum seen so far.

Here is a step-by-step breakdown of the solution:

  1. Initialize max_sum to 0.
  2. Calculate the total sum of the array and store it in a variable, say total_sum.
  3. Iterate through the array, subtracting each element from total_sum. Store this new sum in another variable, say new_sum.
  4. Compare new_sum with max_sum. If new_sum is greater than max_sum, update max_sum.
  5. Finally, return max_sum.

The time complexity of the algorithm is O(n), where n is the size of the array, as we are doing a single pass through the array. The space complexity is O(1), as we are not using any additional space that scales with the input size.

Optimized Solutions

Java

View on GeeksforGeeks
public class Main {
    public static int findMaxSum(int[] arr) {
        int total_sum = 0;
        for (int num : arr) {
            total_sum += num;
        }
        
        int max_sum = total_sum;
        for (int i = 0; i < arr.length; i++) {
            int new_sum = total_sum - arr[i];
            if (new_sum > max_sum) {
                max_sum = new_sum;
            }
        }
        
        return max_sum;
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4};
        System.out.println(findMaxSum(arr));
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.