---
# System prepended metadata

title: Untitled

---




```java
Best Time to Buy and Sell Stock

You are given an array prices where prices[i] is the price of a given stock on the ith day.

You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.


Input: prices = [7,1,5,3,6,4]
Output: 5

Input: prices = [7,6,4,3,1]
Output: 0
```

min = 1
maxProfit = 5 -> result

 0 1 2 3 4 5
[7,1,5,3,6,4,8]
   b     s b s

```java=

private int getMaxProfit(int[] array) {
    if (array.length == 0) return 0;
    
    int min = array[0];
    int maxProfit = 0;
    
    for (int i = 0; i < array.length; i ++) {
        if (min < array[i]) {
            maxProfit = Math.max(maxProfit, array[i] - min);
        }
        min = Math.min(min, array[i]);
    }
    
    return maxProfit;
}

```

Previous states:
1. bought a stock.
2. sell a stock before, buy it again.

```java=
private int getMaxProfit(int[] array) {
    int[] buy
    int[] sell
    int maxProfit = 0;
    
    for (int i = 0; i < array.length; i ++) {
    
    }
}
```

buy[]
sell[]

[7,1,5,3,6,4,8]

```swift=
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public var val: Int
 *     public var next: ListNode?
 *     public init() { self.val = 0; self.next = nil; }
 *     public init(_ val: Int) { self.val = val; self.next = nil; }
 *     public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }
 * }
 */THINK ALOUD
class Solution {
    var mergedList: ListNode?
    func mergeTwoLists(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
        var l1 = l1
        var l2 = l1
        var dummy = ListNode(-1) // current
        var head = dummy
        
        // Part 1 while(l1 != nil && l2 != nil) list same length (Comparing mode val)
        while(l1 != nil && l2 != nil) {
            if l1.val < l2.val {
                dummy.next = l1
                l1 = l1.next
            } else { // l1.val >= l2.val
                dummy.next = l2
                l2 = l2.next
            }
            dummy = dummy.next
        }
        
        // Part 2 
        //[1,2,3]
        //[2,3] -> nil
        if l1 != nil {
            dummy.next = l1
        } else { // l2 != nil
            dummy.next = l2
        }
        
        return head.next  
    }
    
    mergeTwoLists(l1, l2)
    mergeTwoLists(l3, l4)
    merged = l1+l2+l3+l4
}
    
```