I haven't analyzed it closely, but it seems to me your idea for the lazy farmer is a little too greedy. I am having a hard time visualizing your linked list, or the operations on it.
I think a good way to think about this, without worrying about efficiency, is to cast this into a graph, where each day is a node in the graph.
If we have an industrious trader willing to visit the market as often as possible, it looks like Figure 1 below, where I've taken the first few days of your example. Arcs are drawn from every day to every later day in the graph, and the arcs are weighted as follows:
- Consecutive days must have an arc-- either weighted with the profit of buying and then selling on the next day, or (if such an activity would be a loss) weighted zero
- Non-consecutive days only need an arc if the profit is positive. (Although you could draw in the zero-weight arcs for non-profitable pairs, I have suppressed them below so that the graph is readable.)
This graph takes O(N^2) comparison/subtractions to create. Once you have this graph, finding the best plan for the farmer is equivalent to finding the longest path (e.g., the path from the first day to the last day with the largest sum of arc values) through the graph. Usually, finding the longest path through the graph is NP-Complete, but in this case, we have a directed acyclic graph-- you can simply negate all the edge weights and find the shortest path with Dijkstra's algorithm in polynomial time.
To deal with a lazy farmer, you need to adapt this graph structure in such a way that it "counts" the non-zero arcs. We do this by making the graph bigger. A lot bigger. If the farmer is willing to make k trips to the market, he has floor(k/2) buy/sell pairs. Let's call that number X, and draw the nodes of our graph each X+1 times.
Each consecutive arc in the same row (regardless of profit for that day) has a weight of 0. The arcs of positive length are redirected to the row below. Figure 2 shows what this looks like if the farmer is willing to make 4 trips to the market, for 2 total buy/sell opportunities. You also add a dummy "terminal node" that you can get to from the end of each row, at no cost.
You can see that this "counts" the profit arcs by ensuring that each opportunity to profit moves from row to row, and there is never an opportunity to use the same row more than once. So again, you can find the longest path to find the right answer; and again the graph is directed acyclic so this can be converted to a shortest path problem and solved in polynomial time.
The bad news is, the node and arc count have gone up considerably. Instead of N nodes, you have potentially O(N^2) if k=N. Likewise, instead of O(N^2) arcs, you have O(N^3).
You may be able to do a better in both time and space by casting the problem as a grid, similar to the longest common subsequence problem, but this at least illustrates the structure of the problem.