-
Notifications
You must be signed in to change notification settings - Fork 295
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
5209fd8
commit 94cd3b5
Showing
2 changed files
with
33 additions
and
24 deletions.
There are no files selected for viewing
24 changes: 0 additions & 24 deletions
24
Optimization Algorithms/Best Time To Buy and Sell/Program.c
This file was deleted.
Oops, something went wrong.
33 changes: 33 additions & 0 deletions
33
Optimization Algorithms/Best Time To Buy and Sell/Programbest.c
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
#include <stdio.h> | ||
|
||
int maxProfit(int* prices, int pricesSize) { | ||
if (pricesSize <= 1) return 0; // No profit can be made | ||
|
||
int minPrice = prices[0]; // Initialize minPrice to the first price | ||
int maxProfit = 0; // Initialize maxProfit to 0 | ||
|
||
for (int i = 1; i < pricesSize; i++) { | ||
// Update minPrice if the current price is lower | ||
if (prices[i] < minPrice) { | ||
minPrice = prices[i]; | ||
} else { | ||
// Calculate profit if we sell at the current price | ||
int profit = prices[i] - minPrice; | ||
if (profit > maxProfit) { | ||
maxProfit = profit; // Update maxProfit if the current profit is higher | ||
} | ||
} | ||
} | ||
|
||
return maxProfit; // Return the maximum profit found | ||
} | ||
|
||
int main() { | ||
int prices[] = {7, 1, 5, 3, 6, 4}; // Example prices | ||
int size = sizeof(prices) / sizeof(prices[0]); | ||
|
||
int result = maxProfit(prices, size); | ||
printf("The maximum profit is: %d\n", result); | ||
|
||
return 0; | ||
} |