Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 730383
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T06:54:19+00:00 2026-05-14T06:54:19+00:00

I have the following problem: I am given a tree with N apples, for

  • 0

I have the following problem: I am given a tree with N apples, for each apple I am given it’s weight and height. I can pick apples up to a given height H, each time I pick an apple the height of every apple is increased with U. I have to find out the maximum weight of apples I can pick.

1 ≤ N ≤ 100000
0 < {H, U, apples’ weight and height, maximum weight} < 231

Example:

N=4  H=100  U=10  

height weight  
  82     30
  91     10
  93      5
  94     15

The answer is 45: first pick the apple with the weight of 15 then the one with the weight of 30.

Could someone help me approach this problem?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-14T06:54:20+00:00Added an answer on May 14, 2026 at 6:54 am

    Work backwards. Start by deciding the last apple you will pick, then the second to last, etc.

    import heapq
    
    def solve(apples, H, U):
      """Solve apple-picking problem.
    
      apples must be a sequence of (H, W) pairs.
      """
      if U == 0:
        return sum(x[1] for x in apples if x[0] <= H)
    
      apples = sorted(apples, reversed=True)
      # also creates a copy, to not modify caller's data
    
      picked_weight = 0
      available_weights = []  # stored negative for heapq
    
      offset = U - H % U
      if offset == U: offset = 0
      top = offset - U
    
      while (apples or available_weights) and top <= H:
        if available_weights:
          picked_weight += -heapq.heappop(available_weights)
          top += U
        else:
          top += U * max(1, (apples[-1][0] - top) // U)
    
        while apples and apples[0][0] <= top:
          heapq.heappush(available_weights, -apples.pop()[1])
    
      return picked_weight
    

    Simple test:

    def test(expected, apples, H, U):
      actual = solve(apples, H, U)
      if expected != actual:
        print "expected=%r actual=%r | H=%r U=%r apples=%r" % (
                  expected,   actual,     H,   U,   apples)
    
    test(45, [(82, 30), (91, 10), (93,  5), (94, 15)], 100, 10)
    test(22, [( 1,  1), ( 2,  1), (81, 10), (82, 10)], 100, 10)
    test(20, [( 1, 10), ( 2, 10), (11,  1)], 20, 10)
    test(20, [(81, 10), (82, 10), (90,  5)], 100, 10)
    test(1, [(2**31 - 1, 1)], 2**31 - 1, 1)
    

    Someone requested C++, so here it is. It’s nearly identical code and logic to the above Python, except for one change: C++ stdlib’s heap functions work with the max value instead of the min, so no need for the negation. (I kept this self-contained, but utilities such as a heap adapter and container inserter will make the code easier to use.)

    #include <cstdio>
    #include <algorithm>
    #include <iostream>
    #include <numeric>
    #include <vector>
    
    
    struct Apple {
      int h, w;
    
      friend bool operator<(Apple const& a, Apple const& b) {
        return a.h < b.h or (a.h == b.h and a.w < b.w);
      }
      friend bool operator>(Apple const& a, Apple const& b) {
        return b < a;
      }
      friend std::ostream& operator<<(std::ostream& s, Apple const& v) {
        s << '(' << v.h << ", " << v.w << ')';
        return s;
      }
    };
    
    template<class T, class C, T C::*M>
    struct sum {
      T operator()(T const& cur, C const& next) { return cur + next.*M; }
    };
    
    int solve(std::vector<Apple> apples, int H, int U) {
      if (U == 0) {
        return std::accumulate(apples.begin(), apples.end(), 0, sum<int, Apple, &Apple::w>());
      }
    
      std::sort(apples.begin(), apples.end(), std::greater<Apple>());
    
      int picked_weight = 0;
      std::vector<int> available_weights;  // NOT stored negative, unlike Python code
    
      int offset = U - H % U;
      if (offset == U) offset = 0;
      int top = offset - U;
    
      while ((apples.size() or available_weights.size()) and top <= H) {
        if (available_weights.size()) {
          picked_weight += available_weights.front();
          std::pop_heap(available_weights.begin(), available_weights.end());
          available_weights.pop_back();
          top += U;
        }
        else {
          top += U * std::max(1, (apples.back().h - top) / U);
        }
    
        while (apples.size() and apples.back().h <= top) {
          available_weights.push_back(apples.back().w);
          std::push_heap(available_weights.begin(), available_weights.end());
          apples.pop_back();
        }
      }
    
      return picked_weight;
    }
    

    C++ tests:

    template<int N>
    void test(int expected, Apple (&apples)[N], int H, int U) {
      std::vector<Apple> v (apples, apples + N);
      int actual = solve(v, H, U);
      if (expected != actual) {
        std::printf("expected=%d actual=%d | H=%d U=%d apples=[",
                        expected,   actual,     H,   U);
        std::vector<Apple>::const_iterator i = v.begin();
        if (i != v.end()) {
          std::cout << *i;
          for (++i; i != v.end(); ++i) {
            std::cout << ", " << *i;
          }
        }
        std::cout << "]" << std::endl;
      }
    }
    
    int main() {
      {
        Apple data[] = {{82, 30}, {91, 10}, {93,  5}, {94, 15}};
        test(45, data, 100, 10);
      }
      {
        Apple data[] = {{ 1,  1}, { 2,  1}, {81, 10}, {82, 10}};
        test(22, data, 100, 10);
      }
      {
        Apple data[] = {{ 1, 10}, { 2, 10}, {11,  1}};
        test(20, data, 20, 10);
      }
      {
        Apple data[] = {{81, 10}, {82, 10}, {90,  5}};
        test(20, data, 100, 10);
      }
      {
        int n = 2147483647; // 2**31 - 1
        Apple data[] = {{n, 1}};
        test(1, data, n, 1);
      }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

i have the following problem Given a string, return a cleaned string where adjacent
I have the following problem: I have a given number of identically formed items
Recently in a job interview, I was given the following problem. Say I have
I have the following problem: I have an HTML textbox ( <input type=text> )
I have the following problem using subversion: I'm currently working on the trunk of
I have the following problem using template instantiation [*]. file foo.h class Foo {
I have the following problem in my Data Structures and Problem Solving using Java
I have the following problem: I open the dialog, open the SIP keyboard to
I have the following problem. If I query values with a keyfigure which is
Avast there fellow programmers! I have the following problem: I have two rectangles overlapping

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.