Best Time to Buy and Sell Stock
Question
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Example 1:
|
|
Example 2:
|
|
Analysis
循环过程中每次记录当前最小的min,并且在当前价格与min差值最大的时候更新max
Code
|
|
Best Time to Buy and Sell Stock II
Question
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
Analysis
计算所有后者大于前者的元素对的差值并且求值即可
Code
|
|
Best Time to Buy and Sell Stock III
Question
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most two transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
Analysis
Code
|
|
近期评论